Skip to content

GLib

API reference for the GLib namespace (version 2.0), generated from GObject-Introspection.

Classes

  • Allocator
  • Array — Contains the public fields of a GArray.
  • AsyncQueue — An opaque data structure which represents an asynchronous queue. It should only be accessed through the g_async_queue_* functions.
  • BookmarkFileGBookmarkFile lets you parse, edit or create files containing bookmarks. Bookmarks refer to a URI, along with some meta-data about the…
  • ByteArray — Contains the public fields of a GByteArray.
  • Bytes — A simple reference counted data type representing an immutable sequence of zero or more bytes from an unspecified origin. The purpose of a…
  • Cache — A GCache allows sharing of complex data structures, in order to save system resources. GCache uses keys and values. A GCache key…
  • Checksum — GLib provides a generic API for computing checksums (or ‘digests’) for a sequence of arbitrary bytes, using various hashing algorithms like…
  • CompletionGCompletion provides support for automatic completion of a string using any group of target strings. It is typically used for file name…
  • Cond — The Cond struct is an opaque data structure that represents a condition. Threads can block on a Cond if they find a certain condition to be…
  • Data — An opaque data structure that represents a keyed data list. See also: Keyed data lists.
  • DateGDate is a struct for calendrical calculations. The GDate data structure represents a day between January 1, Year 1, and sometime a few…
  • DateTimeGDateTime is a structure that combines a Gregorian date and time into a single structure. GDateTime provides many conversion and…
  • DebugKey — Associates a string with a bit flag. Used in parse_debug_string.
  • Dir — An opaque structure representing an opened directory.
  • DoubleIEEE754 — The FloatIEEE754 and DoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are…
  • Error — The GError structure contains information about an error that has occurred.
  • FloatIEEE754 — The FloatIEEE754 and DoubleIEEE754 unions are used to access the sign, mantissa and exponent of IEEE floats and doubles. These unions are…
  • HashTable — The HashTable struct is an opaque data structure to represent a Hash Table. It should only be accessed via the following functions.
  • HashTableIter — A GHashTableIter structure represents an iterator that can be used to iterate over the elements of a HashTable. GHashTableIter structures…
  • Hmac — HMACs should be used when producing a cookie or hash based on data and a key. Simple mechanisms for using SHA1 and other algorithms to…
  • Hook — The Hook struct represents a single hook function in a HookList.
  • HookList — The HookList struct represents a list of hook functions.
  • IOChannel — The GIOChannel data type aims to provide a portable method for using file descriptors, pipes, and sockets, and integrating them into the…
  • IOFuncs — A table of functions used to handle different types of IOChannel in a generic way.
  • KeyFileGKeyFile parses .ini-like config files. GKeyFile lets you parse, edit or create files containing groups of key-value pairs, which we…
  • List — The List struct is used for each element in a doubly-linked list.
  • LogField — Structure representing a single field in a structured log entry. See g_log_structured() for details. Log fields may contain arbitrary…
  • MainContext — The GMainContext struct is an opaque data type representing a set of sources to be handled in a main loop.
  • MainLoop — The GMainLoop struct is an opaque data type representing the main event loop of a GLib or GTK application.
  • MappedFile — The MappedFile represents a file mapping created with MappedFile.new. It has only private members and should not be accessed directly.
  • MarkupParseContext — A parse context is used to parse a stream of bytes that you expect to contain marked-up text. See MarkupParseContext.new, MarkupParser, and…
  • MarkupParser — Any of the fields in MarkupParser can be None, in which case they will be ignored. Except for the error function, any of these…
  • MatchInfo — A GMatchInfo is an opaque struct used to return information about matches.
  • MemChunk
  • MemVTable — A set of functions used to perform memory allocation. The same MemVTable must be used for all allocations in the same program; a call to…
  • Mutex — The Mutex struct is an opaque data structure to represent a mutex (mutual exclusion). It can be used to protect data against shared access.…
  • Node — The Node struct represents one node in a n-ary tree.
  • Once — A Once struct controls a one-time initialization function. Any one-time initialization function must have its own unique Once struct.
  • OptionContext — A GOptionContext struct defines which options are accepted by the commandline option parser. The struct has only private fields and…
  • OptionEntry — - OptionArg.NONE: gboolean - OptionArg.STRING: gchar - OptionArg.INT: gint - OptionArg.FILENAME: gchar - OptionArg.STRING_ARRAY:…
  • OptionGroup — A GOptionGroup struct defines the options in a single group. The struct has only private fields and should not be directly accessed. All…
  • PathBufGPathBuf is a helper type that allows you to easily build paths from individual elements, using the platform specific conventions for…
  • PatternSpec — A GPatternSpec struct is the ‘compiled’ form of a glob-style pattern. The pattern_match_simple and PatternSpec.match functions match a…
  • PollFD — Represents a file descriptor, which events to poll for, and which events occurred.
  • Private — The Private struct is an opaque data structure to represent a thread-local data key. It is approximately equivalent to the…
  • PtrArray — Contains the public fields of a GPtrArray.
  • Queue — Contains the public fields of a Queue.
  • RWLock — The GRWLock struct is an opaque data structure to represent a reader-writer lock. It is similar to a Mutex in that it allows multiple…
  • Rand — The GRand struct is an opaque data structure. It should only be accessed through the g_rand_* functions.
  • RecMutex — The GRecMutex struct is an opaque data structure to represent a recursive mutex. It is similar to a Mutex with the difference that it is…
  • Regex — A GRegex is a compiled form of a regular expression. After instantiating a GRegex, you can use its methods to find matches in a string,…
  • Relation — A GRelation is a table of data which can be indexed on any number of fields, rather like simple database tables. A GRelation contains a…
  • SList — The SList struct is used for each element in the singly-linked list.
  • ScannerGScanner provides a general-purpose lexical scanner. You should set input_name after creating the scanner, since it is used by the…
  • ScannerConfig — Specifies the Scanner parser configuration. Most settings can be changed during the parsing phase and will affect the lexical parsing of…
  • Sequence — The Sequence struct is an opaque data type representing a sequence data type.
  • SequenceIter — The SequenceIter struct is an opaque data type representing an iterator pointing into a Sequence.
  • Source — The GSource struct is an opaque data type representing an event source.
  • SourceCallbackFuncs — The GSourceCallbackFuncs struct contains functions for managing callback objects.
  • SourceFuncs — The GSourceFuncs struct contains a table of functions used to handle event sources in a generic manner. For idle sources, the prepare and…
  • SourcePrivate
  • StatBuf — A type corresponding to the appropriate struct type for the stat() system call, depending on the platform and/or compiler being used. See…
  • String — A GString is an object that handles the memory management of a C string. The emphasis of GString is on text, typically UTF-8.…
  • StringChunkGStringChunk provides efficient storage of groups of strings String chunks are used to store groups of strings. Memory is allocated in…
  • StrvBuilderGStrvBuilder is a helper object to build a None-terminated string arrays. The following example shows how to build a two element array:…
  • TestCase — An opaque structure representing a test case.
  • TestConfig
  • TestLogBuffer
  • TestLogMsg
  • TestSuite — An opaque structure representing a test suite.
  • Thread — The Thread struct represents a running thread. This struct is returned by Thread.new or Thread.try_new. You can obtain the Thread struct…
  • ThreadPool — The GThreadPool struct represents a thread pool. A thread pool is useful when you wish to asynchronously fork out the execution of work…
  • TimeVal — Represents a precise time, with seconds and microseconds. Similar to the struct timeval returned by the gettimeofday() UNIX system call.…
  • TimeZone — A GTimeZone represents a time zone, at no particular point in time. The GTimeZone struct is refcounted and immutable. Each time zone…
  • TimerGTimer records a start time, and counts microseconds elapsed since that time. This is done somewhat differently on different platforms,…
  • TokenValue — A union holding the value of the token.
  • TrashStack — A GTrashStack is an efficient way to keep a stack of unused allocated memory chunks. Each memory chunk is required to be large enough to…
  • Tree — The GTree struct is an opaque data structure representing a balanced binary tree. It should be accessed only by using the following…
  • TreeNode — An opaque type which identifies a specific node in a Tree.
  • Tuples — The Tuples struct is used to return records (or tuples) from the Relation by g_relation_select(). It only contains one public member - the…
  • Uri — The GUri type and related functions can be used to parse URIs into their components, and build valid URIs from individual components.…
  • UriParamsIter — Many URI schemes include one or more attribute/value pairs as part of the URI value. For example…
  • VariantGVariant is a variant datatype; it can contain one or more values along with information about the type of the values. A GVariant may…
  • VariantBuilder — A utility type for constructing container-type Variant instances. This is an opaque structure and may only be accessed using the following…
  • VariantDict — VariantDict is a mutable interface to Variant dictionaries. It can be used for doing a sequence of dictionary lookups in an efficient way…
  • VariantType — A type in the Variant type system. Variant types are represented as strings, but have a strict syntax described below. All VariantTypes…

Functions

access

def access(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: int) -> int

A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence.

On Windows, the file protection mechanism is not at all POSIX-like, and the underlying function in the C library only checks the FAT-style READONLY attribute, and does not look at the ACL of a file at all. This function is this in practise almost useless on Windows. Software that needs to handle file permissions on Windows more exactly should use the Win32 API.

See your C library manual for more details about access().

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • mode — as in access()

aligned_alloc

def aligned_alloc(n_blocks: int, n_block_bytes: int, alignment: int) -> int | None

This function is similar to malloc, allocating (n_blocks * n_block_bytes) bytes, but care is taken to align the allocated memory to with the given alignment value. Additionally, it will detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Aligned memory allocations returned by this function can only be freed using aligned_free_sized or aligned_free.

Parameters:

  • n_blocks — the number of blocks to allocate
  • n_block_bytes — the size of each block in bytes
  • alignment — the alignment to be enforced, which must be a positive power of 2 and a multiple of sizeof(void*)

aligned_alloc0

def aligned_alloc0(n_blocks: int, n_block_bytes: int, alignment: int) -> int | None

This function is similar to aligned_alloc, but it will also clear the allocated memory before returning it.

Parameters:

  • n_blocks — the number of blocks to allocate
  • n_block_bytes — the size of each block in bytes
  • alignment — the alignment to be enforced, which must be a positive power of 2 and a multiple of sizeof(void*)

aligned_free

def aligned_free(mem: int | None = ...) -> None

Frees the memory allocated by aligned_alloc.

Parameters:

  • mem — the memory to deallocate

aligned_free_sized

def aligned_free_sized(mem: int | None, alignment: int, size: int) -> None

Frees the memory pointed to by mem, assuming it is has the given size and alignment.

If mem is None this is a no-op (and size is ignored).

It is an error if size doesn’t match the size, or alignment doesn’t match the alignment, passed when mem was allocated. size and alignment are passed to this function to allow optimizations in the allocator. If you don’t know either of them, use aligned_free instead.

Parameters:

  • mem — the memory to free
  • alignment — alignment of mem
  • size — size of mem, in bytes

ascii_digit_value

def ascii_digit_value(c: int) -> int

Determines the numeric value of a character as a decimal digit. If the character is not a decimal digit according to GLib.ascii_isdigit, -1 is returned.

Differs from unichar_digit_value because it takes a char, so there's no worry about sign extension if characters are signed.

Parameters:

  • c — an ASCII character

ascii_dtostr

def ascii_dtostr(buffer: str, buf_len: int, d: float) -> str

Converts a gdouble to a string, using the '.' as decimal point.

This function generates enough precision that converting the string back using ascii_strtod gives the same machine-number (on machines with IEEE compatible 64bit doubles). It is guaranteed that the size of the resulting string will never be larger than ASCII_DTOSTR_BUF_SIZE bytes, including the terminating nul character, which is always added.

Parameters:

  • buffer — a buffer to place the resulting string in
  • buf_len — the length of the buffer
  • d — the value to convert

ascii_formatd

def ascii_formatd(buffer: str, buf_len: int, format: str, d: float) -> str

Converts a gdouble to a string, using the '.' as decimal point. To format the number you pass in a printf()-style format string. Allowed conversion specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.

The format must just be a single format specifier starting with %, expecting a gdouble argument.

The returned buffer is guaranteed to be nul-terminated.

If you just want to want to serialize the value into a string, use ascii_dtostr.

Parameters:

  • buffer — a buffer to place the resulting string in
  • buf_len — the length of the buffer
  • format — the printf()-style format to use for the code to use for converting
  • d — the value to convert

ascii_strcasecmp

def ascii_strcasecmp(s1: str, s2: str) -> int

Compare two strings, ignoring the case of ASCII characters.

Unlike the BSD strcasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII bytes as if they are not letters.

This function should be used only on strings that are known to be in encodings where the bytes corresponding to ASCII letters always represent themselves. This includes UTF-8 and the ISO-8859-* charsets, but not for instance double-byte encodings like the Windows Codepage 932, where the trailing bytes of double-byte characters include all ASCII letters. If you compare two CP932 strings using this function, you will get false matches.

Both s1 and s2 must be non-NULL.

Parameters:

  • s1 — string to compare with s2
  • s2 — string to compare with s1

ascii_strdown

def ascii_strdown(str: str, len: int) -> str

Converts all upper case ASCII letters to lower case ASCII letters, with semantics that exactly match ascii_tolower.

Parameters:

  • str — a string
  • len — length of str in bytes, or -1 if str is nul-terminated

ascii_string_to_signed

def ascii_string_to_signed(str: str, base: int, min: int, max: int) -> tuple[bool, int]

A convenience function for converting a string to a signed number.

This function assumes that str contains only a number of the given base that is within inclusive bounds limited by min and max. If this is true, then the converted number is stored in out_num. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input.

base can be between 2 and 36 inclusive. Hexadecimal numbers must not be prefixed with "0x" or "0X". Such a problem does not exist for octal numbers, since they were usually prefixed with a zero which does not change the value of the parsed number.

Parsing failures result in an error with the G_NUMBER_PARSER_ERROR domain. If the input is invalid, the error code will be NumberParserError.INVALID. If the parsed number is out of bounds - NumberParserError.OUT_OF_BOUNDS.

See ascii_strtoll if you have more complex needs such as parsing a string which starts with a number, but then has other characters.

Parameters:

  • str — a string to convert
  • base — base of a parsed number
  • min — a lower bound (inclusive)
  • max — an upper bound (inclusive)

ascii_string_to_unsigned

def ascii_string_to_unsigned(str: str, base: int, min: int, max: int) -> tuple[bool, int]

A convenience function for converting a string to an unsigned number.

This function assumes that str contains only a number of the given base that is within inclusive bounds limited by min and max. If this is true, then the converted number is stored in out_num. An empty string is not a valid input. A string with leading or trailing whitespace is also an invalid input. A string with a leading sign (- or +) is not a valid input for the unsigned parser.

base can be between 2 and 36 inclusive. Hexadecimal numbers must not be prefixed with "0x" or "0X". Such a problem does not exist for octal numbers, since they were usually prefixed with a zero which does not change the value of the parsed number.

Parsing failures result in an error with the G_NUMBER_PARSER_ERROR domain. If the input is invalid, the error code will be NumberParserError.INVALID. If the parsed number is out of bounds - NumberParserError.OUT_OF_BOUNDS.

See ascii_strtoull if you have more complex needs such as parsing a string which starts with a number, but then has other characters.

Parameters:

  • str — a string
  • base — base of a parsed number
  • min — a lower bound (inclusive)
  • max — an upper bound (inclusive)

ascii_strncasecmp

def ascii_strncasecmp(s1: str, s2: str, n: int) -> int

Compare s1 and s2, ignoring the case of ASCII characters and any characters after the first n in each string. If either string is less than n bytes long, comparison will stop at the first nul byte encountered.

Unlike the BSD strncasecmp() function, this only recognizes standard ASCII letters and ignores the locale, treating all non-ASCII characters as if they are not letters.

The same warning as in ascii_strcasecmp applies: Use this function only on strings known to be in encodings where bytes corresponding to ASCII letters always represent themselves.

Parameters:

  • s1 — string to compare with s2
  • s2 — string to compare with s1
  • n — number of characters to compare

ascii_strtod

def ascii_strtod(nptr: str) -> tuple[float, str]

Converts a string to a floating point value.

This function behaves like the standard strtod() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe. A limitation of the implementation is that this function will still accept localized versions of infinities and NANs.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtod() function.

To convert from a gdouble to a string in a locale-insensitive way, use ascii_dtostr.

If the correct value would cause overflow, plus or minus HUGE_VAL is returned (according to the sign of the value), and ERANGE is stored in errno. If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.

This function resets errno before calling strtod() so that you can reliably detect overflow and underflow.

Parameters:

  • nptr — the string to convert to a numeric value

ascii_strtoll

def ascii_strtoll(nptr: str, base: int) -> tuple[int, str]

Converts a string to a gint64 value.

This function behaves like the standard strtoll() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoll() function.

If the correct value would cause overflow, MAXINT64 or MININT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

Parameters:

  • nptr — the string to convert to a numeric value
  • base — to be used for the conversion, 2..36 or 0

ascii_strtoull

def ascii_strtoull(nptr: str, base: int) -> tuple[int, str]

Converts a string to a guint64 value.

This function behaves like the standard strtoull() function does in the C locale. It does this without actually changing the current locale, since that would not be thread-safe.

Note that input with a leading minus sign (-) is accepted, and will return the negation of the parsed number, unless that would overflow a guint64. Critically, this means you cannot assume that a short fixed length input will result in a low return value, as the input could have a leading -.

This function is typically used when reading configuration files or other non-user input that should be locale independent. To handle input from the user you should normally use the locale-sensitive system strtoull() function.

If the correct value would cause overflow, MAXUINT64 is returned, and ERANGE is stored in errno. If the base is outside the valid range, zero is returned, and EINVAL is stored in errno. If the string conversion fails, zero is returned, and endptr returns nptr (if endptr is non-NULL).

Parameters:

  • nptr — the string to convert to a numeric value
  • base — to be used for the conversion, 2..36 or 0

ascii_strup

def ascii_strup(str: str, len: int) -> str

Converts all lower case ASCII letters to upper case ASCII letters, with semantics that exactly match ascii_toupper.

Parameters:

  • str — a string
  • len — length of str in bytes, or -1 if str is nul-terminated

ascii_tolower

def ascii_tolower(c: int) -> int

Convert a character to ASCII lower case. If the character is not an ASCII upper case letter, it is returned unchanged.

Unlike the standard C library tolower() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are lower case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

Parameters:

  • c — any character

ascii_toupper

def ascii_toupper(c: int) -> int

Convert a character to ASCII upper case. If the character is not an ASCII lower case letter, it is returned unchanged.

Unlike the standard C library toupper() function, this only recognizes standard ASCII letters and ignores the locale, returning all non-ASCII characters unchanged, even if they are upper case letters in a particular character set. Also unlike the standard library function, this takes and returns a char, not an int, so don't call it on EOF but no need to worry about casting to guchar before passing a possibly non-ASCII character in.

Parameters:

  • c — any character

ascii_xdigit_value

def ascii_xdigit_value(c: int) -> int

Determines the numeric value of a character as a hexadecimal digit. If the character is not a hex digit according to GLib.ascii_isxdigit, -1 is returned.

Differs from unichar_xdigit_value because it takes a char, so there's no worry about sign extension if characters are signed.

Differs from unichar_xdigit_value because it takes a char, so there's no worry about sign extension if characters are signed.

Parameters:

  • c — an ASCII character

assert_warning

def assert_warning(log_domain: str, file: str, line: int, pretty_function: str, expression: str) -> None

assertion_message

def assertion_message(domain: str, file: str, line: int, func: str, message: str) -> None

assertion_message_cmpint

def assertion_message_cmpint(domain: str, file: str, line: int, func: str, expr: str, arg1: int, cmp: str, arg2: int, numtype: int) -> None

assertion_message_cmpstr

def assertion_message_cmpstr(domain: str, file: str, line: int, func: str, expr: str, arg1: str, cmp: str, arg2: str) -> None

assertion_message_cmpstrv

def assertion_message_cmpstrv(domain: str, file: str, line: int, func: str, expr: str, arg1: str, arg2: str, first_wrong_idx: int) -> None

assertion_message_error

def assertion_message_error(domain: str, file: str, line: int, func: str, expr: str, error: Error, error_domain: Quark, error_code: int) -> None

atexit

def atexit(func: VoidFunc) -> None

:::warning Deprecated since 2.32 This API is deprecated. :::

Specifies a function to be called at normal program termination.

Since GLib 2.8.2, on Windows atexit actually is a preprocessor macro that maps to a call to the atexit() function in the C library. This means that in case the code that calls atexit, i.e. atexit(), is in a DLL, the function will be called when the DLL is detached from the program. This typically makes more sense than that the function is called when the GLib DLL is detached, which happened earlier when atexit was a function in the GLib DLL.

The behaviour of atexit() in the context of dynamically loaded modules is not formally specified and varies wildly.

On POSIX systems, calling atexit (or atexit()) in a dynamically loaded module which is unloaded before the program terminates might well cause a crash at program exit.

Some POSIX systems implement atexit() like Windows, and have each dynamically loaded module maintain an own atexit chain that is called when the module is unloaded.

On other POSIX systems, before a dynamically loaded module is unloaded, the registered atexit functions (if any) residing in that module are called, regardless where the code that registered them resided. This is presumably the most robust approach.

As can be seen from the above, for portability it's best to avoid calling atexit (or atexit()) except in the main executable of a program.

Parameters:

  • func — the function to call on normal program termination.

atomic_int_add

def atomic_int_add(atomic: int | None, val: int) -> int

Atomically adds val to the value of atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic += val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

Before version 2.30, this function did not return a value (but atomic_int_exchange_and_add did, and had the same meaning).

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint
  • val — the value to add

atomic_int_and

def atomic_int_and(atomic: int | None, val: int) -> int

Performs an atomic bitwise 'and' of the value of atomic and val, storing the result back in atomic.

This call acts as a full compiler and hardware memory barrier.

Think of this operation as an atomic version of { tmp = *atomic; *atomic &= val; return tmp; }.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint
  • val — the value to 'and'

atomic_int_compare_and_exchange

def atomic_int_compare_and_exchange(atomic: int | None, oldval: int, newval: int) -> bool

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint
  • oldval — the value to compare with
  • newval — the value to conditionally replace with

atomic_int_compare_and_exchange_full

def atomic_int_compare_and_exchange_full(atomic: int | None, oldval: int, newval: int) -> tuple[bool, int]

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs. In any case the value of atomic before this operation is stored in preval.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { *preval = *atomic; if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

See also atomic_int_compare_and_exchange

Parameters:

  • atomic — a pointer to a #gint or #guint
  • oldval — the value to compare with
  • newval — the value to conditionally replace with

atomic_int_dec_and_test

def atomic_int_dec_and_test(atomic: int | None = ...) -> bool

Decrements the value of atomic by 1.

Think of this operation as an atomic version of { *atomic -= 1; return (*atomic == 0); }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint

atomic_int_exchange

def atomic_int_exchange(atomic: int | None, newval: int) -> int

Sets the atomic to newval and returns the old value from atomic.

This exchange is done atomically.

Think of this operation as an atomic version of { tmp = *atomic; *atomic = val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

Parameters:

  • atomic — a pointer to a #gint or #guint
  • newval — the value to replace with

atomic_int_exchange_and_add

def atomic_int_exchange_and_add(atomic: int | None, val: int) -> int

:::warning Deprecated since 2.30 This API is deprecated. :::

This function existed before atomic_int_add returned the prior value of the integer (which it now does). It is retained only for compatibility reasons. Don't use this function in new code.

Parameters:

  • atomic — a pointer to a #gint
  • val — the value to add

atomic_int_get

def atomic_int_get(atomic: int | None = ...) -> int

Gets the current value of atomic.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint

atomic_int_inc

def atomic_int_inc(atomic: int | None = ...) -> None

Increments the value of atomic by 1.

Think of this operation as an atomic version of { *atomic += 1; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint

atomic_int_or

def atomic_int_or(atomic: int | None, val: int) -> int

Performs an atomic bitwise 'or' of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic |= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint
  • val — the value to 'or'

atomic_int_set

def atomic_int_set(atomic: int | None, newval: int) -> None

Sets the value of atomic to newval.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint
  • newval — a new value to store

atomic_int_xor

def atomic_int_xor(atomic: int | None, val: int) -> int

Performs an atomic bitwise 'xor' of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic ^= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gint or #guint
  • val — the value to 'xor'

atomic_pointer_add

def atomic_pointer_add(atomic: int, val: int) -> int

Atomically adds val to the value of atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic += val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

In GLib 2.80, the return type was changed from #gssize to #gintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

Parameters:

  • atomic — a pointer to a #gpointer-sized value
  • val — the value to add

atomic_pointer_and

def atomic_pointer_and(atomic: int, val: int) -> int

Performs an atomic bitwise 'and' of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic &= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

In GLib 2.80, the return type was changed from #gsize to #guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

Parameters:

  • atomic — a pointer to a #gpointer-sized value
  • val — the value to 'and'

atomic_pointer_compare_and_exchange

def atomic_pointer_compare_and_exchange(atomic: int, oldval: int | None = ..., newval: int | None = ...) -> bool

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gpointer-sized value
  • oldval — the value to compare with
  • newval — the value to conditionally replace with

atomic_pointer_compare_and_exchange_full

def atomic_pointer_compare_and_exchange_full(atomic: int, oldval: int | None = ..., newval: int | None = ...) -> tuple[bool, int]

Compares atomic to oldval and, if equal, sets it to newval. If atomic was not equal to oldval then no change occurs. In any case the value of atomic before this operation is stored in preval.

This compare and exchange is done atomically.

Think of this operation as an atomic version of { *preval = *atomic; if (*atomic == oldval) { *atomic = newval; return TRUE; } else return FALSE; }.

This call acts as a full compiler and hardware memory barrier.

See also atomic_pointer_compare_and_exchange

Parameters:

  • atomic — a pointer to a #gpointer-sized value
  • oldval — the value to compare with
  • newval — the value to conditionally replace with

atomic_pointer_exchange

def atomic_pointer_exchange(atomic: int | None = ..., newval: int | None = ...) -> int | None

Sets the atomic to newval and returns the old value from atomic.

This exchange is done atomically.

Think of this operation as an atomic version of { tmp = *atomic; *atomic = val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

Parameters:

  • atomic — a pointer to a #gpointer-sized value
  • newval — the value to replace with

atomic_pointer_get

def atomic_pointer_get(atomic: int) -> int | None

Gets the current value of atomic.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gpointer-sized value

atomic_pointer_or

def atomic_pointer_or(atomic: int, val: int) -> int

Performs an atomic bitwise 'or' of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic |= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

In GLib 2.80, the return type was changed from #gsize to #guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

Parameters:

  • atomic — a pointer to a #gpointer-sized value
  • val — the value to 'or'

atomic_pointer_set

def atomic_pointer_set(atomic: int, newval: int | None = ...) -> None

Sets the value of atomic to newval.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

Parameters:

  • atomic — a pointer to a #gpointer-sized value
  • newval — a new value to store

atomic_pointer_xor

def atomic_pointer_xor(atomic: int, val: int) -> int

Performs an atomic bitwise 'xor' of the value of atomic and val, storing the result back in atomic.

Think of this operation as an atomic version of { tmp = *atomic; *atomic ^= val; return tmp; }.

This call acts as a full compiler and hardware memory barrier.

While atomic has a volatile qualifier, this is a historical artifact and the pointer passed to it should not be volatile.

In GLib 2.80, the return type was changed from #gsize to #guintptr to add support for platforms with 128-bit pointers. This should not affect existing code.

Parameters:

  • atomic — a pointer to a #gpointer-sized value
  • val — the value to 'xor'

atomic_rc_box_acquire

def atomic_rc_box_acquire(mem_block: int) -> int

Atomically acquires a reference on the data pointed by mem_block.

Parameters:

  • mem_block — a pointer to reference counted data

atomic_rc_box_alloc

def atomic_rc_box_alloc(block_size: int) -> int

Allocates block_size bytes of memory, and adds atomic reference counting semantics to it.

The data will be freed when its reference count drops to zero.

The allocated data is guaranteed to be suitably aligned for any built-in type.

Parameters:

  • block_size — the size of the allocation, must be greater than 0

atomic_rc_box_alloc0

def atomic_rc_box_alloc0(block_size: int) -> int

Allocates block_size bytes of memory, and adds atomic reference counting semantics to it.

The contents of the returned data is set to zero.

The data will be freed when its reference count drops to zero.

The allocated data is guaranteed to be suitably aligned for any built-in type.

Parameters:

  • block_size — the size of the allocation, must be greater than 0

atomic_rc_box_dup

def atomic_rc_box_dup(block_size: int, mem_block: int) -> int

Allocates a new block of data with atomic reference counting semantics, and copies block_size bytes of mem_block into it.

Parameters:

  • block_size — the number of bytes to copy, must be greater than 0
  • mem_block — the memory to copy

atomic_rc_box_get_size

def atomic_rc_box_get_size(mem_block: int) -> int

Retrieves the size of the reference counted data pointed by mem_block.

Parameters:

  • mem_block — a pointer to reference counted data

atomic_rc_box_release

def atomic_rc_box_release(mem_block: int) -> None

Atomically releases a reference on the data pointed by mem_block.

If the reference was the last one, it will free the resources allocated for mem_block.

Parameters:

  • mem_block — a pointer to reference counted data

atomic_rc_box_release_full

def atomic_rc_box_release_full(mem_block: int, clear_func: DestroyNotify) -> None

Atomically releases a reference on the data pointed by mem_block.

If the reference was the last one, it will call clear_func to clear the contents of mem_block, and then will free the resources allocated for mem_block.

Note that implementing weak references via clear_func is not thread-safe: clearing a pointer to the memory from the callback can race with another thread trying to access it as mem_block already has a reference count of 0 when the callback is called and will be freed.

Parameters:

  • mem_block — a pointer to reference counted data
  • clear_func — a function to call when clearing the data

atomic_ref_count_compare

def atomic_ref_count_compare(arc: int, val: int) -> bool

Atomically compares the current value of arc with val.

Parameters:

  • arc — the address of an atomic reference count variable
  • val — the value to compare

atomic_ref_count_dec

def atomic_ref_count_dec(arc: int) -> bool

Atomically decreases the reference count.

If True is returned, the reference count reached 0. After this point, arc is an undefined state and must be reinitialized with atomic_ref_count_init to be used again.

Parameters:

  • arc — the address of an atomic reference count variable

atomic_ref_count_inc

def atomic_ref_count_inc(arc: int) -> None

Atomically increases the reference count.

Parameters:

  • arc — the address of an atomic reference count variable

atomic_ref_count_init

def atomic_ref_count_init() -> int

Initializes a reference count variable to 1.

base64_decode

def base64_decode(text: str) -> list[int]

Decode a sequence of Base-64 encoded text into binary data. Note that the returned binary data is not necessarily zero-terminated, so it should not be used as a character string.

Parameters:

  • text — zero-terminated string with base64 text to decode

base64_decode_inplace

def base64_decode_inplace(text: list[int]) -> tuple[int, list[int]]

Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.

Parameters:

  • text — zero-terminated string with base64 text to decode

base64_encode

def base64_encode(data: list[int] | None = ...) -> str

Encode a sequence of binary data into its Base-64 stringified representation.

Parameters:

  • data — the binary data to encode

base64_encode_close

def base64_encode_close(break_lines: bool, state: int, save: int) -> tuple[int, list[int], int, int]

Flush the status from a sequence of calls to base64_encode_step.

The output buffer must be large enough to fit all the data that will be written to it. It will need up to 4 bytes, or up to 5 bytes if line-breaking is enabled.

The out array will not be automatically nul-terminated.

Parameters:

base64_encode_step

def base64_encode_step(in_: list[int], break_lines: bool, state: int, save: int) -> tuple[int, list[int], int, int]

Incrementally encode a sequence of binary data into its Base-64 stringified representation. By calling this function multiple times you can convert data in chunks to avoid having to have the full encoded data in memory.

When all of the data has been converted you must call base64_encode_close to flush the saved state.

The output buffer must be large enough to fit all the data that will be written to it. Due to the way base64 encodes you will need at least: (len / 3 + 1) * 4 + 4 bytes (+ 4 may be needed in case of non-zero state). If you enable line-breaking you will need at least: ((len / 3 + 1) * 4 + 4) / 76 + 1 bytes of extra space.

break_lines is typically used when putting base64-encoded data in emails. It breaks the lines at 76 columns instead of putting all of the text on the same line. This avoids problems with long lines in the email system. Note however that it breaks the lines with LF characters, not CR LF sequences, so the result cannot be passed directly to SMTP or certain other protocols.

Parameters:

  • in_ — the binary data to encode
  • break_lines — whether to break long lines
  • state — Saved state between steps, initialize to 0
  • save — Saved state between steps, initialize to 0

basename

def basename(file_name: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str

:::warning Deprecated since 2.2 This API is deprecated. :::

Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.

Parameters:

  • file_name — the name of the file

bit_lock

def bit_lock(address: int | None, lock_bit: int) -> None

Sets the indicated lock_bit in address. If the bit is already set, this call will block until bit_unlock unsets the corresponding bit.

Attempting to lock on two different bits within the same integer is not supported and will very probably cause deadlocks.

The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

Parameters:

  • address — a pointer to an integer
  • lock_bit — a bit value between 0 and 31

bit_lock_and_get

def bit_lock_and_get(address: int | None, lock_bit: int) -> int

Sets the indicated lock_bit in address and atomically returns the new value.

This is like bit_lock, except it can atomically return the new value at address (right after obtaining the lock). Thus the value returned in out_val always has the lock_bit set.

Parameters:

  • address — a pointer to an integer
  • lock_bit — a bit value between 0 and 31

bit_nth_lsf

def bit_nth_lsf(mask: int, nth_bit: int) -> int

Find the position of the first bit set in mask, searching from (but not including) nth_bit upwards. Bits are numbered from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nth_bit to -1.

Parameters:

  • mask — a #gulong containing flags
  • nth_bit — the index of the bit to start the search from

bit_nth_msf

def bit_nth_msf(mask: int, nth_bit: int) -> int

Find the position of the first bit set in mask, searching from (but not including) nth_bit downwards. Bits are numbered from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nth_bit to -1 or GLIB_SIZEOF_LONG * 8.

Parameters:

  • mask — a #gulong containing flags
  • nth_bit — the index of the bit to start the search from

bit_storage

def bit_storage(number: int) -> int

Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.

Parameters:

  • number — a #guint

bit_trylock

def bit_trylock(address: int | None, lock_bit: int) -> bool

Sets the indicated lock_bit in address, returning True if successful. If the bit is already set, returns False immediately.

Attempting to lock on two different bits within the same integer is not supported.

The value of the bit that is set is (1u << bit). If bit is not between 0 and 31 then the result is undefined.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

Parameters:

  • address — a pointer to an integer
  • lock_bit — a bit value between 0 and 31

bit_unlock

def bit_unlock(address: int | None, lock_bit: int) -> None

Clears the indicated lock_bit in address. If another thread is currently blocked in bit_lock on this same bit then it will be woken up.

This function accesses address atomically. All other accesses to address must be atomic in order for this function to work reliably. While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

Parameters:

  • address — a pointer to an integer
  • lock_bit — a bit value between 0 and 31

bit_unlock_and_set

def bit_unlock_and_set(address: int | None, lock_bit: int, new_val: int, preserve_mask: int) -> None

This is like bit_unlock but also atomically sets address to val.

If preserve_mask is not zero, then the preserve_mask bits will be preserved in address and are not set to val.

Note that the lock_bit bit will always be unset regardless of val, preserve_mask and the currently set value in address.

Parameters:

  • address — a pointer to an integer
  • lock_bit — a bit value between 0 and 31
  • new_val — the new value to set
  • preserve_mask — mask for bits from address to preserve

blow_chunks

def blow_chunks() -> None

:::warning Deprecated since 2.10 This API is deprecated. :::

build_filenamev

def build_filenamev(args: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]]) -> str

Creates a filename from a vector of elements using the correct separator for the current platform.

This function behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

If you are building a path programmatically you may want to use PathBuf instead.

Parameters:

  • argsNone-terminated array of strings containing the path elements.

build_pathv

def build_pathv(separator: str, args: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]]) -> str

Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of variadic arguments.

This function is mainly meant for language bindings.

Parameters:

  • separator — a string used to separate the elements of the path.
  • argsNone-terminated array of strings containing the path elements.

canonicalize_filename

def canonicalize_filename(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], relative_to: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = ...) -> str

Gets the canonical file name from filename. All triple slashes are turned into single slashes, and all .. and .s resolved against relative_to.

Symlinks are not followed, and the returned path is guaranteed to be absolute.

If filename is an absolute path, relative_to is ignored. Otherwise, relative_to will be prepended to filename to make it absolute. relative_to must be an absolute path, or None. If relative_to is None, it'll fallback to get_current_dir.

This function never fails, and will canonicalize file paths even if they don't exist.

No file system I/O is done.

Parameters:

  • filename — the name of the file
  • relative_to — the relative directory, or None to use the current working directory

chdir

def chdir(path: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> int

A wrapper for the POSIX chdir() function. The function changes the current directory of the process to path.

See your C library manual for more details about chdir().

Parameters:

  • path — a pathname in the GLib file name encoding (UTF-8 on Windows)

check_version

def check_version(required_major: int, required_minor: int, required_micro: int) -> str | None

Checks that the GLib library in use is compatible with the given version.

Generally you would pass in the constants MAJOR_VERSION, MINOR_VERSION, MICRO_VERSION as the three arguments to this function; that produces a check that the library in use is compatible with the version of GLib the application or module was compiled against.

Compatibility is defined by two things: first the version of the running library is newer than the version @required_major.required_minor.@required_micro. Second the running library must be binary compatible with the version @required_major.@required_minor.@required_micro (same major version.)

Parameters:

  • required_major — the required major version
  • required_minor — the required minor version
  • required_micro — the required micro version

child_watch_add

def child_watch_add(priority: int, pid: Pid, function: ChildWatchFunc) -> int

Sets a function to be called when the child indicated by pid exits, at the priority priority.

If you obtain pid from spawn_async or spawn_async_with_pipes you will need to pass SpawnFlags.DO_NOT_REAP_CHILD as a flag to the spawn function for the child watching to work.

In many programs, you will want to call spawn_check_wait_status in the callback to determine whether or not the child exited successfully.

Also, note that on platforms where GLib.Pid must be explicitly closed (see spawn_close_pid) pid must not be closed while the source is still active. Typically, you should invoke spawn_close_pid in the callback function for the source.

GLib supports only a single callback per process ID. On POSIX platforms, the same restrictions mentioned for child_watch_source_new apply to this function.

This internally creates a main loop source using child_watch_source_new and attaches it to the main loop context using Source.attach. You can do these steps manually if you need greater control.

Parameters:

  • priority — the priority of the idle source; typically this will be in the range between PRIORITY_DEFAULT_IDLE and PRIORITY_HIGH_IDLE
  • pid — process to watch — on POSIX systems, this is the positive PID of a child process; on Windows it is a handle for a process (which doesn’t have to be a child)
  • function — function to call

child_watch_source_new

def child_watch_source_new(pid: Pid) -> Source

Creates a new child watch source.

The source will not initially be associated with any MainContext and must be added to one with Source.attach before it will be executed.

Note that child watch sources can only be used in conjunction with g_spawn... when the SpawnFlags.DO_NOT_REAP_CHILD flag is used.

Note that on platforms where GLib.Pid must be explicitly closed (see spawn_close_pid) pid must not be closed while the source is still active. Typically, you will want to call spawn_close_pid in the callback function for the source.

On POSIX platforms, the following restrictions apply to this API due to limitations in POSIX process interfaces:

  • pid must be a child of this process.
  • pid must be positive.
  • The application must not call waitpid() with a non-positive first argument, for instance in another thread.
  • The application must not wait for pid to exit by any other mechanism, including waitpid(pid, ...) or a second child-watch source for the same pid.
  • The application must not ignore SIGCHLD.
  • Before 2.78, the application could not send a signal (kill()) to the watched pid in a race free manner. Since 2.78, you can do that while the associated MainContext is acquired.
  • Before 2.78, even after destroying the Source, you could not be sure that pid wasn’t already reaped. Hence, it was also not safe to kill() or waitpid() on the process ID after the child watch source was gone. Destroying the source before it fired made it impossible to reliably reap the process.

If any of those conditions are not met, this and related APIs will not work correctly. This can often be diagnosed via a GLib warning stating that ECHILD was received by waitpid().

Calling waitpid() for specific processes other than pid remains a valid thing to do.

Parameters:

  • pid — process to watch — on POSIX systems, this is the positive PID of a child process; on Windows it is a handle for a process (which doesn’t have to be a child)

chmod

def chmod(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: int) -> int

A wrapper for the POSIX chmod() function. The chmod() function is used to set the permissions of a file system object.

On Windows the file protection mechanism is not at all POSIX-like, and the underlying chmod() function in the C library just sets or clears the FAT-style READONLY attribute. It does not touch any ACL. Software that needs to manage file permissions on Windows exactly should use the Win32 API.

See your C library manual for more details about chmod().

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • mode — as in chmod()

clear_error

def clear_error() -> None

If err or *err is None, does nothing. Otherwise, calls Error.free on *err and sets *err to None.

close

def close(fd: int) -> bool

This wraps the close() call. In case of error, errno will be preserved, but the error will also be stored as a Error in error. In case of success, errno is undefined.

Besides using Error, there is another major reason to prefer this function over the call provided by the system; on Unix, it will attempt to correctly handle EINTR, which has platform-specific semantics.

It is a bug to call this function with an invalid file descriptor.

On POSIX platforms since GLib 2.76, this function is async-signal safe if (and only if) error is None and fd is a valid open file descriptor. This makes it safe to call from a signal handler or a GSpawnChildSetupFunc under those conditions. See signal(7) and signal-safety(7) for more details.

Parameters:

  • fd — A file descriptor

compute_checksum_for_bytes

def compute_checksum_for_bytes(checksum_type: ChecksumType | int, data: Bytes) -> str | None

Computes the checksum for a binary data. This is a convenience wrapper for Checksum.new, Checksum.get_string and Checksum.free.

The hexadecimal string returned will be in lower case.

Parameters:

  • checksum_type — a ChecksumType
  • data — binary blob to compute the digest of

compute_checksum_for_data

def compute_checksum_for_data(checksum_type: ChecksumType | int, data: list[int]) -> str | None

Computes the checksum for a binary data of length. This is a convenience wrapper for Checksum.new, Checksum.get_string and Checksum.free.

The hexadecimal string returned will be in lower case.

Parameters:

  • checksum_type — a ChecksumType
  • data — binary blob to compute the digest of

compute_checksum_for_string

def compute_checksum_for_string(checksum_type: ChecksumType | int, str: str, length: int) -> str | None

Computes the checksum of a string.

The hexadecimal string returned will be in lower case.

Parameters:

  • checksum_type — a ChecksumType
  • str — the string to compute the checksum of
  • length — the length of the string, or -1 if the string is null-terminated.

compute_hmac_for_bytes

def compute_hmac_for_bytes(digest_type: ChecksumType | int, key: Bytes, data: Bytes) -> str

Computes the HMAC for a binary data. This is a convenience wrapper for Hmac.new, Hmac.get_string and Hmac.unref.

The hexadecimal string returned will be in lower case.

Parameters:

  • digest_type — a ChecksumType to use for the HMAC
  • key — the key to use in the HMAC
  • data — binary blob to compute the HMAC of

compute_hmac_for_data

def compute_hmac_for_data(digest_type: ChecksumType | int, key: list[int], data: list[int]) -> str

Computes the HMAC for a binary data of length. This is a convenience wrapper for Hmac.new, Hmac.get_string and Hmac.unref.

The hexadecimal string returned will be in lower case.

Parameters:

  • digest_type — a ChecksumType to use for the HMAC
  • key — the key to use in the HMAC
  • data — binary blob to compute the HMAC of

compute_hmac_for_string

def compute_hmac_for_string(digest_type: ChecksumType | int, key: list[int], str: str, length: int) -> str

Computes the HMAC for a string.

The hexadecimal string returned will be in lower case.

Parameters:

  • digest_type — a ChecksumType to use for the HMAC
  • key — the key to use in the HMAC
  • str — the string to compute the HMAC for
  • length — the length of the string, or -1 if the string is nul-terminated

convert

def convert(str: list[int], to_codeset: str, from_codeset: str) -> tuple[list[int], int]

Converts a string from one character set to another.

Note that you should use g_iconv() for streaming conversions. Despite the fact that bytes_read can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won't be preserved across successive calls to convert, g_convert_with_iconv() or convert_with_fallback. (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

Using extensions such as "//TRANSLIT" may not work (or may not work well) on many platforms. Consider using str_to_ascii instead.

Parameters:

  • str — the string to convert.
  • to_codeset — name of character set into which to convert str
  • from_codeset — character set of str.

convert_error_quark

def convert_error_quark() -> Quark

convert_with_fallback

def convert_with_fallback(str: list[int], to_codeset: str, from_codeset: str, fallback: str) -> tuple[list[int], int]

Converts a string from one character set to another, possibly including fallback sequences for characters not representable in the output. Note that it is not guaranteed that the specification for the fallback sequences in fallback will be honored. Some systems may do an approximate conversion from from_codeset to to_codeset in their iconv() functions, in which case GLib will simply return that approximate conversion.

Note that you should use g_iconv() for streaming conversions. Despite the fact that bytes_read can return information about partial characters, the g_convert_... functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won't be preserved across successive calls to convert, g_convert_with_iconv() or convert_with_fallback. (An example of this is the GNU C converter for CP1255 which does not emit a base character until it knows that the next character is not a mark that could combine with the base character.)

Parameters:

  • str — the string to convert.
  • to_codeset — name of character set into which to convert str
  • from_codeset — character set of str.
  • fallback — UTF-8 string to use in place of characters not present in the target encoding. (The string must be representable in the target encoding). If None, characters not in the target encoding will be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.

creat

def creat(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: int) -> int

A wrapper for the POSIX creat() function. The creat() function is used to convert a pathname into a file descriptor, creating a file if necessary.

On POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements creat() and file descriptors. The actual Windows API for opening files is different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.

Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().

See your C library manual for more details about creat().

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • mode — as in creat()

datalist_foreach

def datalist_foreach(datalist: Data, func: DataForeachFunc) -> None

Calls the given function for each data element of the datalist. The function is called with each data element's GQuark id and data, together with the given user_data parameter. Note that this function is NOT thread-safe. So unless datalist can be protected from any modifications during invocation of this function, it should not be called.

func can make changes to datalist, but the iteration will not reflect changes made during the datalist_foreach call, other than skipping over elements that are removed.

Parameters:

  • datalist — a datalist.
  • func — the function to call for each data element.

datalist_get_data

def datalist_get_data(datalist: Data, key: str) -> int | None

Gets a data element, using its string identifier. This is slower than datalist_id_get_data because it compares strings.

Parameters:

  • datalist — a datalist.
  • key — the string identifying a data element.

datalist_get_flags

def datalist_get_flags(datalist: Data) -> int

Gets flags values packed in together with the datalist. See datalist_set_flags.

Parameters:

  • datalist — pointer to the location that holds a list

datalist_id_get_data

def datalist_id_get_data(datalist: Data, key_id: Quark) -> int | None

Retrieves the data element corresponding to key_id.

Parameters:

  • datalist — a datalist.
  • key_id — the GQuark identifying a data element.

datalist_id_remove_multiple

def datalist_id_remove_multiple(datalist: Data, keys: list[Quark]) -> None

Removes multiple keys from a datalist.

This is more efficient than calling g_datalist_id_remove_data() multiple times in a row.

Before 2.80, n_keys had to be not larger than 16. Since 2.84, performance is improved for larger number of keys.

Parameters:

  • datalist — a datalist
  • keys — keys to remove

datalist_set_flags

def datalist_set_flags(datalist: Data, flags: int) -> None

Turns on flag values for a data list. This function is used to keep a small number of boolean flags in an object with a data list without using any additional space. It is not generally useful except in circumstances where space is very tight. (It is used in the base GObject.Object type, for example.)

Parameters:

  • datalist — pointer to the location that holds a list
  • flags — the flags to turn on. The values of the flags are restricted by DATALIST_FLAGS_MASK (currently 3; giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.

datalist_unset_flags

def datalist_unset_flags(datalist: Data, flags: int) -> None

Turns off flag values for a data list. See datalist_unset_flags

Parameters:

  • datalist — pointer to the location that holds a list
  • flags — the flags to turn off. The values of the flags are restricted by DATALIST_FLAGS_MASK (currently 3: giving two possible boolean flags). A value for flags that doesn't fit within the mask is an error.

dataset_destroy

def dataset_destroy(dataset_location: int) -> None

Destroys the dataset, freeing all memory allocated, and calling any destroy functions set for data elements.

Parameters:

  • dataset_location — the location identifying the dataset.

dataset_foreach

def dataset_foreach(dataset_location: int, func: DataForeachFunc) -> None

Calls the given function for each data element which is associated with the given location. Note that this function is NOT thread-safe. So unless dataset_location can be protected from any modifications during invocation of this function, it should not be called.

func can make changes to the dataset, but the iteration will not reflect changes made during the dataset_foreach call, other than skipping over elements that are removed.

Parameters:

  • dataset_location — the location identifying the dataset.
  • func — the function to call for each data element.

dataset_id_get_data

def dataset_id_get_data(dataset_location: int, key_id: Quark) -> int | None

Gets the data element corresponding to a GQuark.

Parameters:

  • dataset_location — the location identifying the dataset.
  • key_id — the GQuark id to identify the data element.

dcgettext

def dcgettext(domain: str | None, msgid: str, category: int) -> str

This is a variant of dgettext that allows specifying a locale category instead of always using LC_MESSAGES. See dgettext for more information about how this functions differs from calling dcgettext() directly.

Parameters:

  • domain — the translation domain to use, or None to use the domain set with textdomain()
  • msgid — message to translate
  • category — a locale category

dgettext

def dgettext(domain: str | None, msgid: str) -> str

This function is a wrapper of dgettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.

The advantage of using this function over dgettext() proper is that libraries using this function (like GTK) will not use translations if the application using the library does not have translations for the current locale. This results in a consistent English-only interface instead of one having partial translations. For this feature to work, the call to textdomain() and setlocale() should precede any dgettext invocations. For GTK, it means calling textdomain() before Gtk.init or its variants.

This function disables translations if and only if upon its first call all the following conditions hold:

  • domain is not None

  • textdomain() has been called to set a default text domain

  • there is no translations available for the default text domain and the current locale

  • current locale is not "C" or any English locales (those starting with "en_")

Note that this behavior may not be desired for example if an application has its untranslated messages in a language other than English. In those cases the application should call textdomain() after initializing GTK.

Applications should normally not use this function directly, but use the _() macro for translations.

Parameters:

  • domain — the translation domain to use, or None to use the domain set with textdomain()
  • msgid — message to translate

direct_equal

def direct_equal(v1: int | None = ..., v2: int | None = ...) -> bool

Compares two #gpointer arguments and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using opaque pointers compared by pointer value as keys in a HashTable.

This equality function is also appropriate for keys that are integers stored in pointers, such as GINT_TO_POINTER (n).

Parameters:

  • v1 — a key
  • v2 — a key to compare with v1

direct_hash

def direct_hash(v: int | None = ...) -> int

Converts a gpointer to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using opaque pointers compared by pointer value as keys in a HashTable.

This hash function is also appropriate for keys that are integers stored in pointers, such as GINT_TO_POINTER (n).

Parameters:

  • v — a #gpointer key

dngettext

def dngettext(domain: str | None, msgid: str, msgid_plural: str, n: int) -> str

This function is a wrapper of dngettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.

See dgettext for details of how this differs from dngettext() proper.

Parameters:

  • domain — the translation domain to use, or None to use the domain set with textdomain()
  • msgid — message to translate
  • msgid_plural — plural form of the message
  • n — the quantity for which translation is needed

double_equal

def double_equal(v1: int, v2: int) -> bool

Compares the two #gdouble values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-None pointers to doubles as keys in a HashTable.

Parameters:

  • v1 — a pointer to a #gdouble key
  • v2 — a pointer to a #gdouble key to compare with v1

double_hash

def double_hash(v: int) -> int

Converts a pointer to a #gdouble to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, It can be passed to g_hash_table_new() as the hash_func parameter, when using non-None pointers to doubles as keys in a HashTable.

Parameters:

  • v — a pointer to a #gdouble key

dpgettext

def dpgettext(domain: str | None, msgctxtid: str, msgidoffset: int) -> str

This function is a variant of dgettext which supports a disambiguating message context. GNU gettext uses the '\004' character to separate the message context and message id in msgctxtid. If 0 is passed as msgidoffset, this function will fall back to trying to use the deprecated convention of using "|" as a separation character.

This uses dgettext internally. See that functions for differences with dgettext() proper.

Applications should normally not use this function directly, but use the C_() macro for translations with context.

Parameters:

  • domain — the translation domain to use, or None to use the domain set with textdomain()
  • msgctxtid — a combined message context and message id, separated by a \004 character
  • msgidoffset — the offset of the message id in msgctxid

dpgettext2

def dpgettext2(domain: str | None, context: str, msgid: str) -> str

This function is a variant of dgettext which supports a disambiguating message context. GNU gettext uses the '\004' character to separate the message context and message id in msgctxtid.

This uses dgettext internally. See that functions for differences with dgettext() proper.

This function differs from C_() in that it is not a macro and thus you may use non-string-literals as context and msgid arguments.

Parameters:

  • domain — the translation domain to use, or None to use the domain set with textdomain()
  • context — the message context
  • msgid — the message

environ_getenv

def environ_getenv(envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, variable: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str | None

Returns the value of the environment variable variable in the provided list envp.

Parameters:

  • envp — an environment list (eg, as returned from get_environ), or None for an empty environment list
  • variable — the environment variable to get

environ_setenv

def environ_setenv(envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, variable: str | bytes | os.PathLike[str] | os.PathLike[bytes], value: str | bytes | os.PathLike[str] | os.PathLike[bytes], overwrite: bool) -> list[str]

Sets the environment variable variable in the provided list envp to value.

Parameters:

  • envp — an environment list that can be freed using strfreev (e.g., as returned from get_environ), or None for an empty environment list
  • variable — the environment variable to set, must not contain '='
  • value — the value for to set the variable to
  • overwrite — whether to change the variable if it already exists

environ_unsetenv

def environ_unsetenv(envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, variable: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> list[str]

Removes the environment variable variable from the provided environment envp.

Parameters:

  • envp — an environment list that can be freed using strfreev (e.g., as returned from get_environ), or None for an empty environment list
  • variable — the environment variable to remove, must not contain '='

file_error_from_errno

def file_error_from_errno(err_no: int) -> FileError

Gets a FileError constant based on the passed-in err_no.

For example, if you pass in EEXIST this function returns FileError.EXIST. Unlike errno values, you can portably assume that all FileError values will exist.

Normally a FileError value goes into a Error returned from a function that manipulates files. So you would use file_error_from_errno when constructing a Error.

Parameters:

  • err_no — an "errno" value

file_error_quark

def file_error_quark() -> Quark

file_get_contents

def file_get_contents(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> tuple[bool, list[int]]

Reads an entire file into allocated memory, with good error checking.

If the call was successful, it returns True and sets contents to the file contents and length to the length of the file contents in bytes. The string stored in contents will be nul-terminated, so for text files you can pass None for the length argument. If the call was not successful, it returns False and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the FileError enumeration. In the error case, contents is set to None and length is set to zero.

Parameters:

  • filename — name of a file to read contents from, in the GLib file name encoding

file_open_tmp

def file_open_tmp(tmpl: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = ...) -> tuple[int, str]

Opens a file for writing in the preferred directory for temporary files (as returned by get_tmp_dir).

tmpl should be a string in the GLib file name encoding containing a sequence of six 'X' characters, as the parameter to g_mkstemp(). However, unlike these functions, the template should only be a basename, no directory components are allowed. If template is None, a default template is used.

Note that in contrast to g_mkstemp() (and mkstemp()) tmpl is not modified, and might thus be a read-only literal string.

Upon success, and if name_used is non-None, the actual name used is returned in name_used. This string should be freed with free when not needed any longer. The returned name is in the GLib file name encoding.

Parameters:

  • tmpl — Template for file name, as in g_mkstemp(), basename only, or None for a default template
def file_read_link(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str

Reads the contents of the symbolic link filename like the POSIX readlink() function.

The returned string is in the encoding used for filenames. Use filename_to_utf8 to convert it to UTF-8.

The returned string may also be a relative path. Use g_build_filename() to convert it to an absolute path:

g_autoptr(GError) local_error = NULL;
g_autofree gchar *link_target = g_file_read_link ("/etc/localtime", &local_error);

if (local_error != NULL)
  g_error ("Error reading link: %s", local_error->message);

if (!g_path_is_absolute (link_target))
  {
    g_autofree gchar *absolute_link_target = g_build_filename ("/etc", link_target, NULL);
    g_free (link_target);
    link_target = g_steal_pointer (&absolute_link_target);
  }

Parameters:

  • filename — the symbolic link

file_set_contents

def file_set_contents(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], contents: list[int]) -> bool

Writes all of contents to a file named filename. This is a convenience wrapper around calling file_set_contents_full with flags set to G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING and mode set to 0666.

Parameters:

  • filename — name of a file to write contents to, in the GLib file name encoding
  • contents — string to write to the file

file_set_contents_full

def file_set_contents_full(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], contents: list[int], flags: FileSetContentsFlags | int, mode: int) -> bool

Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

flags control the properties of the write operation: whether it’s atomic, and what the tradeoff is between returning quickly or being resilient to system crashes.

As this function performs file I/O, it is recommended to not call it anywhere where blocking would cause problems, such as in the main loop of a graphical application. In particular, if flags has any value other than FileSetContentsFlags.NONE then this function may call fsync().

If FileSetContentsFlags.CONSISTENT is set in flags, the operation is atomic in the sense that it is first written to a temporary file which is then renamed to the final name.

Notes:

  • On UNIX, if filename already exists hard links to filename will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. If filename is a symbolic link, the link itself will be replaced, not the linked file.

  • On UNIX, if filename already exists and is non-empty, and if the system supports it (via a journalling filesystem or equivalent), and if FileSetContentsFlags.CONSISTENT is set in flags, the fsync() call (or equivalent) will be used to ensure atomic replacement: filename will contain either its old contents or contents, even in the face of system power loss, the disk being unsafely removed, etc.

  • On UNIX, if filename does not already exist or is empty, there is a possibility that system power loss etc. after calling this function will leave filename empty or full of NUL bytes, depending on the underlying filesystem, unless FileSetContentsFlags.DURABLE and FileSetContentsFlags.CONSISTENT are set in flags.

  • On Windows renaming a file will not remove an existing file with the new name, so on Windows there is a race condition between the existing file being removed and the temporary file being renamed.

  • On Windows there is no way to remove a file that is open to some process, or mapped into memory. Thus, this function will fail if filename already exists and is open.

If the call was successful, it returns True. If the call was not successful, it returns False and sets error. The error domain is G_FILE_ERROR. Possible error codes are those in the FileError enumeration.

Note that the name for the temporary file is constructed by appending up to 7 characters to filename.

If the file didn’t exist before and is created, it will be given the permissions from mode. Otherwise, the permissions of the existing file will remain unchanged.

Parameters:

  • filename — name of a file to write contents to, in the GLib file name encoding
  • contents — string to write to the file
  • flags — flags controlling the safety vs speed of the operation
  • mode — file mode, as passed to open(); typically this will be 0666

file_test

def file_test(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], test: FileTest | int) -> bool

Returns True if any of the tests in the bitfield test are True. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR) will return True if the file exists; the check whether it's a directory doesn't matter since the existence test is True. With the current set of available tests, there's no point passing in more than one test at a time.

Apart from FileTest.IS_SYMLINK all tests follow symbolic links, so for a symbolic link to a regular file file_test will return True for both FileTest.IS_SYMLINK and FileTest.IS_REGULAR.

Note, that for a dangling symbolic link file_test will return True for FileTest.IS_SYMLINK and False for all other flags.

You should never use file_test to test whether it is safe to perform an operation, because there is always the possibility of the condition changing before you actually perform the operation, see TOCTOU.

For example, you might think you could use FileTest.IS_SYMLINK to know whether it is safe to write to a file without being tricked into writing into a different location. It doesn't work!

// DON'T DO THIS
 if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
   {
     fd = g_open (filename, O_WRONLY);
     // write to fd
   }

 // DO THIS INSTEAD
 fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
 if (fd == -1)
   {
     // check error
     if (errno == ELOOP)
       // file is a symlink and can be ignored
     else
       // handle errors as before
   }
 else
   {
     // write to fd
   }

Another thing to note is that FileTest.EXISTS and FileTest.IS_EXECUTABLE are implemented using the access() system call. This usually doesn't matter, but if your program is setuid or setgid it means that these tests will give you the answer for the real user ID and group ID, rather than the effective user ID and group ID.

On Windows, there are no symlinks, so testing for FileTest.IS_SYMLINK will always return False. Testing for FileTest.IS_EXECUTABLE will just check that the file exists and its name indicates that it is executable, checking for well-known extensions and those listed in the PATHEXT environment variable.

Parameters:

  • filename — a filename to test in the GLib file name encoding
  • test — bitfield of FileTest flags

filename_display_basename

def filename_display_basename(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str

Returns the display basename for the particular filename, guaranteed to be valid UTF-8. The display name might not be identical to the filename, for instance there might be problems converting it to UTF-8, and some files can be translated in the display.

If GLib cannot make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is "\357\277\275" in octal notation) to find out if filename was in an invalid encoding.

You must pass the whole absolute pathname to this functions so that translation of well known locations can be done.

This function is preferred over filename_display_name if you know the whole path, as it allows translation.

Parameters:

  • filename — an absolute pathname in the GLib file name encoding

filename_display_name

def filename_display_name(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str

Converts a filename into a valid UTF-8 string. The conversion is not necessarily reversible, so you should keep the original around and use the return value of this function only for display purposes. Unlike filename_to_utf8, the result is guaranteed to be non-None even if the filename actually isn't in the GLib file name encoding.

If GLib cannot make sense of the encoding of filename, as a last resort it replaces unknown characters with U+FFFD, the Unicode replacement character. You can search the result for the UTF-8 encoding of this character (which is "\357\277\275" in octal notation) to find out if filename was in an invalid encoding.

If you know the whole pathname of the file you should use filename_display_basename, since that allows location-based translation of filenames.

Parameters:

  • filename — a pathname hopefully in the GLib file name encoding

filename_from_uri

def filename_from_uri(uri: str) -> tuple[str, str]

Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.

Since GLib 2.78, the query string and fragment can be present in the URI, but are not part of the resulting filename. We take inspiration from https://url.spec.whatwg.org/#file-state, but we don't support the entire standard.

Parameters:

  • uri — a uri describing a filename (escaped, encoded in ASCII).

filename_from_utf8

def filename_from_utf8(utf8string: str, len: int) -> tuple[str, int, int]

Converts a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error ConvertError.ILLEGAL_SEQUENCE. If the filename encoding is not UTF-8 and the conversion output contains a nul character, the error ConvertError.EMBEDDED_NUL is set and the function returns None.

Parameters:

  • utf8string — a UTF-8 encoded string.
  • len — the length of the string, or -1 if the string is nul-terminated.

filename_to_uri

def filename_to_uri(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], hostname: str | None = ...) -> str

Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.

Parameters:

  • filename — an absolute filename specified in the GLib file name encoding, which is the on-disk file name bytes on Unix, and UTF-8 on Windows
  • hostname — A UTF-8 encoded hostname, or None for none.

filename_to_utf8

def filename_to_utf8(opsysstring: str | bytes | os.PathLike[str] | os.PathLike[bytes], len: int) -> tuple[str, int, int]

Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the current locale.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error ConvertError.ILLEGAL_SEQUENCE. If the source encoding is not UTF-8 and the conversion output contains a nul character, the error ConvertError.EMBEDDED_NUL is set and the function returns None. Use convert to produce output that may contain embedded nul characters.

Parameters:

  • opsysstring — a string in the encoding for filenames
  • len — the length of the string, or -1 if the string is nul-terminated (Note that some encodings may allow nul bytes to occur inside strings. In that case, using -1 for the len parameter is unsafe)

find_program_in_path

def find_program_in_path(program: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str | None

Locates the first executable named program in the user's path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or None if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and None otherwise.

On Windows, if program does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in the PATHEXT environment variable.

On Windows, it looks for the file in the same way as CreateProcess() would. This means first in the directory where the executing program was loaded from, then in the current directory, then in the Windows 32-bit system directory, then in the Windows directory, and finally in the directories in the PATH environment variable. If the program is found, the return value contains the full name including the type suffix.

Parameters:

  • program — a program name in the GLib file name encoding

fopen

def fopen(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: str) -> int | None

A wrapper for the stdio fopen() function. The fopen() function opens a file and associates a new stream with it.

Because file descriptors are specific to the C library on Windows, and a file descriptor is part of the FILE struct, the FILE* returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the FILE* returned by this function cannot be passed to C library functions like fprintf() or fread().

See your C library manual for more details about fopen().

As close() and fclose() are part of the C library, this implies that it is currently impossible to close a file if the application C library and the C library used by GLib are different. Convenience functions like file_set_contents_full avoid this problem.

Since GLib 2.86, the e option is supported in mode on all platforms. On Unix platforms it will set O_CLOEXEC on the opened file descriptor. On Windows platforms it will be converted to the N modifier. It is recommended to set e unconditionally, unless you know the returned file should be shared between this process and a new fork.

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • mode — a string describing the mode in which the file should be opened

format_size

def format_size(size: int) -> str

Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (kB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.2 MB". The returned string is UTF-8, and may use a non-breaking space to separate the number and units, to ensure they aren’t separated when line wrapped.

The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).

This string should be freed with free when not needed any longer.

See format_size_full for more options about how the size might be formatted.

Parameters:

  • size — a size in bytes

format_size_for_display

def format_size_for_display(size: int) -> str

:::warning Deprecated since 2.30 This API is deprecated. :::

Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.1 MB".

The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).

This string should be freed with free when not needed any longer.

Parameters:

  • size — a size in bytes

format_size_full

def format_size_full(size: int, flags: FormatSizeFlags | int) -> str

Formats a size.

This function is similar to format_size but allows for flags that modify the output. See FormatSizeFlags.

Parameters:

free

def free(mem: int | None = ...) -> None

Frees the memory pointed to by mem.

If you know the allocated size of mem, calling free_sized may be faster, depending on the libc implementation in use.

Starting from GLib 2.78, this may happen automatically in case a GCC compatible compiler is used with some optimization level and the allocated size is known at compile time (see documentation of __builtin_object_size() to understand its caveats).

If mem is None it simply returns, so there is no need to check mem against None before calling this function.

Parameters:

  • mem — the memory to free

free_sized

def free_sized(mem: int | None, size: int) -> None

Frees the memory pointed to by mem, assuming it is has the given size.

If mem is None this is a no-op (and size is ignored).

It is an error if size doesn’t match the size passed when mem was allocated. size is passed to this function to allow optimizations in the allocator. If you don’t know the allocation size, use free instead.

In case a GCC compatible compiler is used, this function may be used automatically via free if the allocated size is known at compile time, since GLib 2.78.

Parameters:

  • mem — the memory to free
  • size — size of mem, in bytes

freopen

def freopen(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: str, stream: int | None = ...) -> int | None

A wrapper for the POSIX freopen() function. The freopen() function opens a file and associates it with an existing stream.

See your C library manual for more details about freopen().

Since GLib 2.86, the e option is supported in mode on all platforms. See the documentation for fopen for more details.

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • mode — a string describing the mode in which the file should be opened
  • stream — an existing stream which will be reused, or None

fsync

def fsync(fd: int) -> int

A wrapper for the POSIX fsync() function. On Windows, _commit() will be used. On macOS, fcntl(F_FULLFSYNC) will be used. The fsync() function is used to synchronize a file's in-core state with that of the disk.

This wrapper will handle retrying on EINTR.

See the C library manual for more details about fsync().

Parameters:

  • fd — a file descriptor

get_application_name

def get_application_name() -> str | None

Gets a human-readable name for the application, as set by set_application_name. This name should be localized if possible, and is intended for display to the user. Contrast with get_prgname, which gets a non-localized name. If set_application_name has not been called, returns the result of get_prgname (which may be None if set_prgname has also not been called).

get_charset

def get_charset() -> tuple[bool, str]

Obtains the character set for the current locale; you might use this character set as an argument to convert, to convert from the current locale's encoding to some other encoding. (Frequently locale_to_utf8 and locale_from_utf8 are nice shortcuts, though.)

On Windows the character set returned by this function is the so-called system default ANSI code-page. That is the character set used by the "narrow" versions of C library and Win32 functions that handle file names. It might be different from the character set used by the C library's current locale.

On Linux, the character set is found by consulting nl_langinfo() if available. If not, the environment variables LC_ALL, LC_CTYPE, LANG and CHARSET are queried in order. nl_langinfo() returns the C locale if no locale has been loaded by setlocale().

The return value is True if the locale's encoding is UTF-8, in that case you can perhaps avoid calling convert.

The string returned in charset is not allocated, and should not be freed.

get_codeset

def get_codeset() -> str

Gets the character set for the current locale.

get_console_charset

def get_console_charset() -> tuple[bool, str]

Obtains the character set used by the console attached to the process, which is suitable for printing output to the terminal.

Usually this matches the result returned by get_charset, but in environments where the locale's character set does not match the encoding of the console this function tries to guess a more suitable value instead.

On Windows the character set returned by this function is the output code page used by the console associated with the calling process. If the codepage can't be determined (for example because there is no console attached) UTF-8 is assumed.

The return value is True if the locale's encoding is UTF-8, in that case you can perhaps avoid calling convert.

The string returned in charset is not allocated, and should not be freed.

get_current_dir

def get_current_dir() -> str

Gets the current directory.

The returned string should be freed when no longer needed. The encoding of the returned string is system defined. On Windows, it is always UTF-8.

Since GLib 2.40, this function will return the value of the "PWD" environment variable if it is set and it happens to be the same as the current directory. This can make a difference in the case that the current directory is the target of a symbolic link.

get_current_time

def get_current_time(result: TimeVal) -> None

:::warning Deprecated since 2.62 This API is deprecated. :::

Queries the system wall-clock time.

This is equivalent to the UNIX gettimeofday() function, but portable.

You may find get_real_time to be more convenient.

Parameters:

  • resultTimeVal structure in which to store current time

get_environ

def get_environ() -> list[str]

Gets the list of environment variables for the current process.

The list is None terminated and each item in the list is of the form 'NAME=VALUE'.

This is equivalent to direct access to the 'environ' global variable, except portable.

The return value is freshly allocated and it should be freed with strfreev when it is no longer needed.

get_filename_charsets

def get_filename_charsets() -> tuple[bool, list[str]]

Determines the preferred character sets used for filenames. The first character set from the charsets is the filename encoding, the subsequent character sets are used when trying to generate a displayable representation of a filename, see filename_display_name.

On Unix, the character sets are determined by consulting the environment variables G_FILENAME_ENCODING and G_BROKEN_FILENAMES. On Windows, the character set used in the GLib API is always UTF-8 and said environment variables have no effect.

G_FILENAME_ENCODING may be set to a comma-separated list of character set names. The special token @locale is taken to mean the character set for the current locale. If G_FILENAME_ENCODING is not set, but G_BROKEN_FILENAMES is, the character set of the current locale is taken as the filename encoding. If neither environment variable is set, UTF-8 is taken as the filename encoding, but the character set of the current locale is also put in the list of encodings.

The returned charsets belong to GLib and must not be freed.

Note that on Unix, regardless of the locale character set or G_FILENAME_ENCODING value, the actual file names present on a system might be in any random encoding or just gibberish.

get_home_dir

def get_home_dir() -> str

Gets the current user's home directory.

As with most UNIX tools, this function will return the value of the HOME environment variable if it is set to an existing absolute path name, falling back to the passwd file in the case that it is unset.

If the path given in HOME is non-absolute, does not exist, or is not a directory, the result is undefined.

Before version 2.36 this function would ignore the HOME environment variable, taking the value from the passwd database instead. This was changed to increase the compatibility of GLib with other programs (and the XDG basedir specification) and to increase testability of programs based on GLib (by making it easier to run them from test frameworks).

If your program has a strong requirement for either the new or the old behaviour (and if you don't wish to increase your GLib dependency to ensure that the new behaviour is in effect) then you should either directly check the HOME environment variable yourself or unset it before calling any functions in GLib.

get_host_name

def get_host_name() -> str

Return a name for the machine.

The returned name is not necessarily a fully-qualified domain name, or even present in DNS or some other name service at all. It need not even be unique on your local network or site, but usually it is. Callers should not rely on the return value having any specific properties like uniqueness for security purposes. Even if the name of the machine is changed while an application is running, the return value from this function does not change. The returned string is owned by GLib and should not be modified or freed. If no name can be determined, a default fixed string "localhost" is returned.

The encoding of the returned string is UTF-8.

get_language_names

def get_language_names() -> list[str]

Computes a list of applicable locale names, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

For example, if LANGUAGE=de:en_US, then the returned list is "de", "en_US", "en", "C".

This function consults the environment variables LANGUAGE, LC_ALL, LC_MESSAGES and LANG to find the list of locales specified by the user.

get_language_names_with_category

def get_language_names_with_category(category_name: str) -> list[str]

Computes a list of applicable locale names with a locale category name, which can be used to construct the fallback locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale "C".

This function consults the environment variables LANGUAGE, LC_ALL, category_name, and LANG to find the list of locales specified by the user.

get_language_names returns get_language_names_with_category("LC_MESSAGES").

Parameters:

  • category_name — a locale category name

get_locale_variants

def get_locale_variants(locale: str) -> list[str]

Returns a list of derived variants of locale, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable. This function handles territory, charset and extra locale modifiers. See setlocale(3) for information about locales and their format.

locale itself is guaranteed to be returned in the output.

For example, if locale is fr_BE, then the returned list is fr_BE, fr. If locale is en_GB.UTF-8@euro, then the returned list is en_GB.UTF-8@euro, en_GB.UTF-8, en_GB@euro, en_GB, en.UTF-8@euro, en.UTF-8, en@euro, en.

If you need the list of variants for the current locale, use get_language_names.

Parameters:

  • locale — a locale identifier

get_monotonic_time

def get_monotonic_time() -> int

Queries the system monotonic time in microseconds.

The monotonic clock will always increase and doesn’t suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.

We try to use the clock that corresponds as closely as possible to the passage of time as measured by system calls such as poll() but it may not always be possible to do this.

A more accurate version of this function exists. get_monotonic_time_ns returns the time in nanoseconds.

get_monotonic_time_ns

def get_monotonic_time_ns() -> int

Queries the system monotonic time in nanoseconds.

The monotonic clock will always increase and doesn’t suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.

We try to use the clock that corresponds as closely as possible to the passage of time as measured by system calls such as poll() but it may not always be possible to do this.

Another version of this function exists. get_monotonic_time returns the time in microseconds. If you want to support older GLib versions, it is an alternative.

get_num_processors

def get_num_processors() -> int

Determine the approximate number of threads that the system will schedule simultaneously for this process. This is intended to be used as a parameter to g_thread_pool_new() for CPU bound tasks and similar cases.

get_os_info

def get_os_info(key_name: str) -> str | None

Get information about the operating system.

On Linux this comes from the /etc/os-release file. On other systems, it may come from a variety of sources. You can either use the standard key names like G_OS_INFO_KEY_NAME or pass any UTF-8 string key name. For example, /etc/os-release provides a number of other less commonly used values that may be useful. No key is guaranteed to be provided, so the caller should always check if the result is None.

Parameters:

  • key_name — a key for the OS info being requested, for example G_OS_INFO_KEY_NAME.

get_prgname

def get_prgname() -> str | None

Gets the name of the program. This name should not be localized, in contrast to get_application_name.

If you are using Gio.Application the program name is set in Gio.Application.run. In case of GDK or GTK it is set in gdk_init(), which is called by Gtk.init and the Gtk.Application::startup handler. The program name is found by taking the last component of argv[0].

get_real_name

def get_real_name() -> str

Gets the real name of the user. This usually comes from the user's entry in the passwd file. The encoding of the returned string is system-defined. (On Windows, it is, however, always UTF-8.) If the real user name cannot be determined, the string "Unknown" is returned.

get_real_time

def get_real_time() -> int

Queries the system wall-clock time.

This is equivalent to the UNIX gettimeofday() function, but portable.

You should only use this call if you are actually interested in the real wall-clock time. get_monotonic_time is probably more useful for measuring intervals.

get_system_config_dirs

def get_system_config_dirs() -> list[str]

Returns an ordered list of base directories in which to access system-wide configuration information.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the list of directories retrieved will be XDG_CONFIG_DIRS.

On Windows it follows XDG Base Directory Specification if XDG_CONFIG_DIRS is defined. If XDG_CONFIG_DIRS is undefined, the directory that contains application data for all users is used instead. A typical path is C:\Documents and Settings\All Users\Application Data. This folder is used for application data that is not user specific. For example, an application can store a spell-check dictionary, a database of clip art, or a log file in the FOLDERID_ProgramData folder. This information will not roam and is available to anyone using the computer.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

get_system_data_dirs

def get_system_data_dirs() -> list[str]

Returns an ordered list of base directories in which to access system-wide application data.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification In this case the list of directories retrieved will be XDG_DATA_DIRS.

On Windows it follows XDG Base Directory Specification if XDG_DATA_DIRS is defined. If XDG_DATA_DIRS is undefined, the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for FOLDERID_ProgramData and FOLDERID_PublicDocuments.

Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.

Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application's .exe file belongs to.

The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder's name is "bin", its parent is used, otherwise the folder itself.

Note that on Windows the returned list can vary depending on where this function is called.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

get_tmp_dir

def get_tmp_dir() -> str

Gets the directory to use for temporary files.

On UNIX, this is taken from the TMPDIR environment variable. If the variable is not set, P_tmpdir is used, as defined by the system C library. Failing that, a hard-coded default of "/tmp" is returned.

On Windows, the TEMP environment variable is used, with the root directory of the Windows installation (eg: "C:\") used as a default.

The encoding of the returned string is system-defined. On Windows, it is always UTF-8. The return value is never None or the empty string.

get_user_cache_dir

def get_user_cache_dir() -> str

Returns a base directory in which to store non-essential, cached data specific to particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_CACHE_HOME.

On Windows it follows XDG Base Directory Specification if XDG_CACHE_HOME is defined. If XDG_CACHE_HOME is undefined, the directory that serves as a common repository for temporary Internet files is used instead. A typical path is C:\Documents and Settings\username\Local Settings\Temporary Internet Files. See the documentation for FOLDERID_InternetCache.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

get_user_config_dir

def get_user_config_dir() -> str

Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_CONFIG_HOME.

On Windows it follows XDG Base Directory Specification if XDG_CONFIG_HOME is defined. If XDG_CONFIG_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for FOLDERID_LocalAppData. Note that in this case on Windows it will be the same as what get_user_data_dir returns.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

get_user_data_dir

def get_user_data_dir() -> str

Returns a base directory in which to access application data such as icons that is customized for a particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_DATA_HOME.

On Windows it follows XDG Base Directory Specification if XDG_DATA_HOME is defined. If XDG_DATA_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for FOLDERID_LocalAppData. Note that in this case on Windows it will be the same as what get_user_config_dir returns.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

get_user_name

def get_user_name() -> str

Gets the user name of the current user. The encoding of the returned string is system-defined. On UNIX, it might be the preferred file name encoding, or something else, and there is no guarantee that it is even consistent on a machine. On Windows, it is always UTF-8.

get_user_runtime_dir

def get_user_runtime_dir() -> str

Returns a directory that is unique to the current user on the local system.

This is determined using the mechanisms described in the XDG Base Directory Specification. This is the directory specified in the XDG_RUNTIME_DIR environment variable. In the case that this variable is not set, we return the value of get_user_cache_dir, after verifying that it exists.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

get_user_special_dir

def get_user_special_dir(directory: UserDirectory | int) -> str | None

Returns the full path of a special directory using its logical id.

On UNIX this is done using the XDG special user directories. For compatibility with existing practise, UserDirectory.DIRECTORY_DESKTOP falls back to $HOME/Desktop when XDG special user directories have not been set up.

Depending on the platform, the user might be able to change the path of the special directory without requiring the session to restart; GLib will not reflect any change once the special directories are loaded.

Parameters:

  • directory — the logical id of special directory

get_user_state_dir

def get_user_state_dir() -> str

Returns a base directory in which to store state files specific to particular user.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification. In this case the directory retrieved will be XDG_STATE_HOME.

On Windows it follows XDG Base Directory Specification if XDG_STATE_HOME is defined. If XDG_STATE_HOME is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See the documentation for FOLDERID_LocalAppData. Note that in this case on Windows it will be the same as what get_user_data_dir returns.

The return value is cached and modifying it at runtime is not supported, as it’s not thread-safe to modify environment variables at runtime.

getenv

def getenv(variable: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str | None

Returns the value of an environment variable.

On UNIX, the name and value are byte strings which might or might not be in some consistent character set and encoding. On Windows, they are in UTF-8. On Windows, in case the environment variable's value contains references to other environment variables, they are expanded.

Parameters:

  • variable — the environment variable to get

hostname_is_ascii_encoded

def hostname_is_ascii_encoded(hostname: str) -> bool

Tests if hostname contains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returns True, you should decode the hostname with hostname_to_unicode before displaying it to the user.

Note that a hostname might contain a mix of encoded and unencoded segments, and so it is possible for hostname_is_non_ascii and hostname_is_ascii_encoded to both return True for a name.

Parameters:

  • hostname — a hostname

hostname_is_ip_address

def hostname_is_ip_address(hostname: str) -> bool

Tests if hostname is the string form of an IPv4 or IPv6 address. (Eg, "192.168.0.1".)

Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).

Parameters:

  • hostname — a hostname (or IP address in string form)

hostname_is_non_ascii

def hostname_is_non_ascii(hostname: str) -> bool

Tests if hostname contains Unicode characters. If this returns True, you need to encode the hostname with hostname_to_ascii before using it in non-IDN-aware contexts.

Note that a hostname might contain a mix of encoded and unencoded segments, and so it is possible for hostname_is_non_ascii and hostname_is_ascii_encoded to both return True for a name.

Parameters:

  • hostname — a hostname

hostname_to_ascii

def hostname_to_ascii(hostname: str) -> str | None

Converts hostname to its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot.

Parameters:

  • hostname — a valid UTF-8 or ASCII hostname

hostname_to_unicode

def hostname_to_unicode(hostname: str) -> str | None

Converts hostname to its canonical presentation form; a UTF-8 string in Unicode normalization form C, containing no uppercase letters, no forbidden characters, and no ASCII-encoded segments, and not ending with a trailing dot.

Of course if hostname is not an internationalized hostname, then the canonical presentation form will be entirely ASCII.

Parameters:

  • hostname — a valid UTF-8 or ASCII hostname

idle_add

def idle_add(priority: int, function: SourceFunc) -> int

Adds a function to be called whenever there are no higher priority events pending.

If the function returns SOURCE_REMOVE it is automatically removed from the list of event sources and will not be called again.

See main loop memory management for details on how to handle the return value and memory management of data.

This internally creates a main loop source using idle_source_new and attaches it to the global MainContext using Source.attach, so the callback will be invoked in whichever thread is running that main context. You can do these steps manually if you need greater control or to use a custom main context.

Parameters:

idle_remove_by_data

def idle_remove_by_data(data: int | None = ...) -> bool

Removes the idle function with the given data.

Parameters:

  • data — the data for the idle source’s callback.

idle_source_new

def idle_source_new() -> Source

Creates a new idle source.

The source will not initially be associated with any MainContext and must be added to one with Source.attach before it will be executed. Note that the default priority for idle sources is PRIORITY_DEFAULT_IDLE, as compared to other sources which have a default priority of PRIORITY_DEFAULT.

int64_equal

def int64_equal(v1: int, v2: int) -> bool

Compares the two #gint64 values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-None pointers to 64-bit integers as keys in a HashTable.

Parameters:

  • v1 — a pointer to a #gint64 key
  • v2 — a pointer to a #gint64 key to compare with v1

int64_hash

def int64_hash(v: int) -> int

Converts a pointer to a #gint64 to a hash value.

It can be passed to g_hash_table_new() as the hash_func parameter, when using non-None pointers to 64-bit integer values as keys in a HashTable.

Parameters:

  • v — a pointer to a #gint64 key

int_equal

def int_equal(v1: int, v2: int) -> bool

Compares the two #gint values being pointed to and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-None pointers to integers as keys in a HashTable.

Note that this function acts on pointers to #gint, not on #gint directly: if your hash table's keys are of the form GINT_TO_POINTER (n), use direct_equal instead.

Parameters:

  • v1 — a pointer to a #gint key
  • v2 — a pointer to a #gint key to compare with v1

int_hash

def int_hash(v: int) -> int

Converts a pointer to a #gint to a hash value. It can be passed to g_hash_table_new() as the hash_func parameter, when using non-None pointers to integer values as keys in a HashTable.

Note that this function acts on pointers to #gint, not on #gint directly: if your hash table's keys are of the form GINT_TO_POINTER (n), use direct_hash instead.

Parameters:

  • v — a pointer to a #gint key

intern_static_string

def intern_static_string(string: str | None = ...) -> str

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp(). intern_static_string does not copy the string, therefore string must not be freed or modified.

This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

Parameters:

  • string — a static string

intern_string

def intern_string(string: str | None = ...) -> str

Returns a canonical representation for string. Interned strings can be compared for equality by comparing the pointers, instead of using strcmp().

This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

Parameters:

  • string — a string

io_add_watch

def io_add_watch(channel: IOChannel, priority: int, condition: IOCondition | int, func: IOFunc) -> int

Adds the IOChannel into the default main loop context with the given priority.

This internally creates a main loop source using io_create_watch and attaches it to the main loop context with Source.attach. You can do these steps manually if you need greater control.

Parameters:

  • channel — a IOChannel
  • priority — the priority of the IOChannel source
  • condition — the condition to watch for
  • func — the function to call when the condition is satisfied

io_create_watch

def io_create_watch(channel: IOChannel, condition: IOCondition | int) -> Source

Creates a Source that's dispatched when condition is met for the given channel. For example, if condition is GObject.IOCondition.IN, the source will be dispatched when there's data available for reading.

The callback function invoked by the Source should be added with Source.set_callback, but it has type GIOFunc (not GSourceFunc).

g_io_add_watch() is a simpler interface to this same functionality, for the case where you want to add the source to the default main loop context at the default priority.

On Windows, polling a Source created to watch a channel for a socket puts the socket in non-blocking mode. This is a side-effect of the implementation and unavoidable.

Parameters:

  • channel — a IOChannel to watch
  • condition — conditions to watch for

listenv

def listenv() -> list[str]

Gets the names of all variables set in the environment.

Programs that want to be portable to Windows should typically use this function and getenv instead of using the environ array from the C library directly. On Windows, the strings in the environ array are in system codepage encoding, while in most of the typical use cases for environment variables in GLib-using programs you want the UTF-8 encoding that this function and getenv provide.

locale_from_utf8

def locale_from_utf8(utf8string: str, len: int) -> tuple[list[int], int]

Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale. On Windows this means the system codepage.

The input string shall not contain nul characters even if the len argument is positive. A nul character found inside the string will result in error ConvertError.ILLEGAL_SEQUENCE. Use convert to convert input that may contain embedded nul characters.

Parameters:

  • utf8string — a UTF-8 encoded string
  • len — the length of the string, or -1 if the string is nul-terminated.

locale_to_utf8

def locale_to_utf8(opsysstring: list[int]) -> tuple[str, int, int]

Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the current locale into a UTF-8 string.

If the source encoding is not UTF-8 and the conversion output contains a nul character, the error ConvertError.EMBEDDED_NUL is set and the function returns None. If the source encoding is UTF-8, an embedded nul character is treated with the ConvertError.ILLEGAL_SEQUENCE error for backward compatibility with earlier versions of this library. Use convert to produce output that may contain embedded nul characters.

Parameters:

  • opsysstring — a string in the encoding of the current locale. On Windows this means the system codepage.

log_default_handler

def log_default_handler(log_domain: str | None, log_level: LogLevelFlags | int, message: str | None = ..., unused_data: int | None = ...) -> None

The default log handler set up by GLib; GLib.log_set_default_handler allows to install an alternate default log handler.

This is used if no log handler has been set for the particular log domain and log level combination. It outputs the message to stderr or stdout and if the log level is fatal it calls GLib.BREAKPOINT. It automatically prints a new-line character after the message, so one does not need to be manually included in message.

The behavior of this log handler can be influenced by a number of environment variables:

  • G_MESSAGES_PREFIXED: A :-separated list of log levels for which messages should be prefixed by the program name and PID of the application.
  • G_MESSAGES_DEBUG: A space-separated list of log domains for which debug and informational messages are printed. By default these messages are not printed. If you need to set the allowed domains at runtime, use log_writer_default_set_debug_domains.
  • DEBUG_INVOCATION: If set to 1, this is equivalent to G_MESSAGES_DEBUG=all. DEBUG_INVOCATION is a standard environment variable set by systemd to prompt debug output. (Since: 2.84)

stderr is used for levels LogLevelFlags.LEVEL_ERROR, LogLevelFlags.LEVEL_CRITICAL, LogLevelFlags.LEVEL_WARNING and LogLevelFlags.LEVEL_MESSAGE. stdout is used for the rest, unless stderr was requested by log_writer_default_set_use_stderr.

This has no effect if structured logging is enabled; see Using Structured Logging.

Parameters:

  • log_domain — the log domain of the message, or NULL for the default "" application domain
  • log_level — the level of the message
  • message — the message
  • unused_data — data passed from GLib.log which is unused

log_get_always_fatal

def log_get_always_fatal() -> LogLevelFlags

Gets the current fatal mask.

This is mostly used by custom log writers to make fatal messages (fatal-warnings, fatal-criticals) work as expected, when using the G_DEBUG environment variable (see Running GLib Applications).

An example usage is shown below:

static GLogWriterOutput
my_custom_log_writer_fn (GLogLevelFlags log_level,
                         const GLogField *fields,
                         gsize n_fields,
                         gpointer user_data)
{

   // abort if the message was fatal
   if (log_level & g_log_get_always_fatal ())
     g_abort ();

   // custom log handling code
   ...
   ...

   // success
   return G_LOG_WRITER_HANDLED;
}

log_get_debug_enabled

def log_get_debug_enabled() -> bool

Return whether debug output from the GLib logging system is enabled.

Note that this should not be used to conditionalise calls to GLib.debug or other logging functions; it should only be used from LogWriterFunc implementations.

Note also that the value of this does not depend on G_MESSAGES_DEBUG, nor DEBUG_INVOCATION, nor log_writer_default_set_debug_domains; see the docs for log_set_debug_enabled.

log_remove_handler

def log_remove_handler(log_domain: str, handler_id: int) -> None

Removes the log handler.

This has no effect if structured logging is enabled; see Using Structured Logging.

Parameters:

  • log_domain — the log domain
  • handler_id — the ID of the handler, which was returned in log_set_handler

log_set_always_fatal

def log_set_always_fatal(fatal_mask: LogLevelFlags | int) -> LogLevelFlags

Sets the message levels which are always fatal, in any log domain.

When a message with any of these levels is logged the program terminates. You can only set the levels defined by GLib to be fatal. LogLevelFlags.LEVEL_ERROR is always fatal.

You can also make some message levels fatal at runtime by setting the G_DEBUG environment variable (see Running GLib Applications).

Libraries should not call this function, as it affects all messages logged by a process, including those from other libraries.

Structured log messages (using GLib.log_structured and log_structured_array) are fatal only if the default log writer is used; otherwise it is up to the writer function to determine which log messages are fatal. See Using Structured Logging.

Parameters:

  • fatal_mask — the mask containing bits set for each level of error which is to be fatal

log_set_debug_enabled

def log_set_debug_enabled(enabled: bool) -> None

Enable or disable debug output from the GLib logging system for all domains.

This value interacts disjunctively with G_MESSAGES_DEBUG, DEBUG_INVOCATION and log_writer_default_set_debug_domains — if any of them would allow a debug message to be outputted, it will be.

Note that this should not be used from within library code to enable debug output — it is intended for external use.

Parameters:

  • enabledTRUE to enable debug output, FALSE otherwise

log_set_fatal_mask

def log_set_fatal_mask(log_domain: str, fatal_mask: LogLevelFlags | int) -> LogLevelFlags

Sets the log levels which are fatal in the given domain.

LogLevelFlags.LEVEL_ERROR is always fatal.

This has no effect on structured log messages (using GLib.log_structured or log_structured_array). To change the fatal behaviour for specific log messages, programs must install a custom log writer function using log_set_writer_func. See Using Structured Logging.

This function is mostly intended to be used with LogLevelFlags.LEVEL_CRITICAL. You should typically not set LogLevelFlags.LEVEL_WARNING, LogLevelFlags.LEVEL_MESSAGE, LogLevelFlags.LEVEL_INFO or LogLevelFlags.LEVEL_DEBUG as fatal except inside of test programs.

Parameters:

  • log_domain — the log domain
  • fatal_mask — the new fatal mask

log_set_handler

def log_set_handler(log_domain: str | None, log_levels: LogLevelFlags | int, log_func: LogFunc) -> int

Like log_set_handler, but takes a destroy notify for the user_data.

This has no effect if structured logging is enabled; see Using Structured Logging.

The log_domain parameter can be set to NULL or an empty string to use the default application domain.

Parameters:

  • log_domain — the log domain application domain
  • log_levels — the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with the LogLevelFlags.FLAG_FATAL and LogLevelFlags.FLAG_RECURSION bit flags.
  • log_func — the log handler function

log_set_writer_func

def log_set_writer_func() -> None

Set a writer function which will be called to format and write out each log message.

Each program should set a writer function, or the default writer (log_writer_default) will be used.

Libraries must not call this function — only programs are allowed to install a writer function, as there must be a single, central point where log messages are formatted and outputted.

There can only be one writer function. It is an error to set more than one.

log_structured_array

def log_structured_array(log_level: LogLevelFlags | int, fields: list[LogField]) -> None

Log a message with structured data.

The message will be passed through to the log writer set by the application using log_set_writer_func. If the message is fatal (i.e. its log level is LogLevelFlags.LEVEL_ERROR), the program will be aborted at the end of this function.

See GLib.log_structured for more documentation.

This assumes that log_level is already present in fields (typically as the PRIORITY field).

Parameters:

  • log_level — log level, either from LogLevelFlags, or a user-defined level
  • fields — key–value pairs of structured data to add to the log message

log_variant

def log_variant(log_domain: str | None, log_level: LogLevelFlags | int, fields: Variant) -> None

Log a message with structured data, accepting the data within a Variant.

This version is especially useful for use in other languages, via introspection.

The only mandatory item in the fields dictionary is the "MESSAGE" which must contain the text shown to the user.

The values in the fields dictionary are likely to be of type G_VARIANT_TYPE_STRING. Array of bytes (G_VARIANT_TYPE_BYTESTRING) is also supported. In this case the message is handled as binary and will be forwarded to the log writer as such. The size of the array should not be higher than G_MAXSSIZE. Otherwise it will be truncated to this size. For other types Variant.print will be used to convert the value into a string.

For more details on its usage and about the parameters, see GLib.log_structured.

Parameters:

  • log_domain — log domain, usually G_LOG_DOMAIN
  • log_level — log level, either from LogLevelFlags, or a user-defined level
  • fields — a dictionary (Variant of the type G_VARIANT_TYPE_VARDICT) containing the key-value pairs of message data.

log_writer_default

def log_writer_default(log_level: LogLevelFlags | int, fields: list[LogField], user_data: int | None = ...) -> LogWriterOutput

Format a structured log message and output it to the default log destination for the platform.

On Linux, this is typically the systemd journal, falling back to stdout or stderr if running from the terminal or if output is being redirected to a file.

Support for other platform-specific logging mechanisms may be added in future. Distributors of GLib may modify this function to impose their own (documented) platform-specific log writing policies.

This is suitable for use as a LogWriterFunc, and is the default writer used if no other is set using log_set_writer_func.

As with log_default_handler, this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in the environment, or set at runtime by log_writer_default_set_debug_domains.

log_writer_default uses the mask set by log_set_always_fatal to determine which messages are fatal. When using a custom writer function instead it is up to the writer function to determine which log messages are fatal.

Parameters:

  • log_level — log level, either from LogLevelFlags, or a user-defined level
  • fields — key–value pairs of structured data forming the log message
  • user_data — user data passed to log_set_writer_func

log_writer_default_set_debug_domains

def log_writer_default_set_debug_domains(domains: str | None = ...) -> None

Reset the list of domains to be logged, that might be initially set by the G_MESSAGES_DEBUG or DEBUG_INVOCATION environment variables.

This function is thread-safe.

Parameters:

  • domainsNULL-terminated array with domains to be printed. NULL or an array with no values means none. Array with a single value "all" means all.

log_writer_default_set_use_stderr

def log_writer_default_set_use_stderr(use_stderr: bool) -> None

Configure whether the built-in log functions will output all log messages to stderr.

The built-in log functions are log_default_handler for the old-style API, and both log_writer_default and log_writer_standard_streams for the structured API.

By default, log messages of levels LogLevelFlags.LEVEL_INFO and LogLevelFlags.LEVEL_DEBUG are sent to stdout, and other log messages are sent to stderr. This is problematic for applications that intend to reserve stdout for structured output such as JSON or XML.

This function sets global state. It is not thread-aware, and should be called at the very start of a program, before creating any other threads or creating objects that could create worker threads of their own.

Parameters:

  • use_stderr — If TRUE, use stderr for log messages that would normally have appeared on stdout

log_writer_default_would_drop

def log_writer_default_would_drop(log_level: LogLevelFlags | int, log_domain: str | None = ...) -> bool

Check whether log_writer_default and log_default_handler would ignore a message with the given domain and level.

As with log_default_handler, this function drops debug and informational messages unless their log domain (or all) is listed in the space-separated G_MESSAGES_DEBUG environment variable, or DEBUG_INVOCATION=1 is set in the environment, or by log_writer_default_set_debug_domains.

This can be used when implementing log writers with the same filtering behaviour as the default, but a different destination or output format:

if (g_log_writer_default_would_drop (log_level, log_domain))
  return G_LOG_WRITER_HANDLED;
]|

or to skip an expensive computation if it is only needed for a debugging
message, and `G_MESSAGES_DEBUG` and `DEBUG_INVOCATION` are not set:

```c
if (![`log_writer_default_would_drop`](./index.md#function-log_writer_default_would_drop) (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN))
  &#123;
    g_autofree gchar *result = expensive_computation (my_object);

    g_debug ("my_object result: `s`", result);
  &#125;

Parameters:

  • log_level — log level, either from LogLevelFlags, or a user-defined level
  • log_domain — log domain

log_writer_format_fields

def log_writer_format_fields(log_level: LogLevelFlags | int, fields: list[LogField], use_color: bool) -> str

Format a structured log message as a string suitable for outputting to the terminal (or elsewhere).

This will include the values of all fields it knows how to interpret, which includes MESSAGE and GLIB_DOMAIN (see the documentation for GLib.log_structured). It does not include values from unknown fields.

The returned string does not have a trailing new-line character. It is encoded in the character set of the current locale, which is not necessarily UTF-8.

Parameters:

  • log_level — log level, either from LogLevelFlags, or a user-defined level
  • fields — key–value pairs of structured data forming the log message
  • use_colorTRUE to use ANSI color escape sequences when formatting the message, FALSE to not

log_writer_is_journald

def log_writer_is_journald(output_fd: int) -> bool

Check whether the given output_fd file descriptor is a connection to the systemd journal, or something else (like a log file or stdout or stderr).

Invalid file descriptors are accepted and return FALSE, which allows for the following construct without needing any additional error handling:

is_journald = g_log_writer_is_journald (fileno (stderr));

Parameters:

  • output_fd — output file descriptor to check

log_writer_journald

def log_writer_journald(log_level: LogLevelFlags | int, fields: list[LogField], user_data: int | None = ...) -> LogWriterOutput

Format a structured log message and send it to the systemd journal as a set of key–value pairs.

All fields are sent to the journal, but if a field has length zero (indicating program-specific data) then only its key will be sent.

This is suitable for use as a LogWriterFunc.

If GLib has been compiled without systemd support, this function is still defined, but will always return LogWriterOutput.UNHANDLED.

Parameters:

  • log_level — log level, either from LogLevelFlags, or a user-defined level
  • fields — key–value pairs of structured data forming the log message
  • user_data — user data passed to log_set_writer_func

log_writer_standard_streams

def log_writer_standard_streams(log_level: LogLevelFlags | int, fields: list[LogField], user_data: int | None = ...) -> LogWriterOutput

Format a structured log message and print it to either stdout or stderr, depending on its log level.

LogLevelFlags.LEVEL_INFO and LogLevelFlags.LEVEL_DEBUG messages are sent to stdout, or to stderr if requested by log_writer_default_set_use_stderr; all other log levels are sent to stderr. Only fields which are understood by this function are included in the formatted string which is printed.

If the output stream supports ANSI color escape sequences, they will be used in the output.

A trailing new-line character is added to the log message when it is printed.

This is suitable for use as a LogWriterFunc.

Parameters:

  • log_level — log level, either from LogLevelFlags, or a user-defined level
  • fields — key–value pairs of structured data forming the log message
  • user_data — user data passed to log_set_writer_func

log_writer_supports_color

def log_writer_supports_color(output_fd: int) -> bool

Check whether the given output_fd file descriptor supports ANSI color escape sequences.

If so, they can safely be used when formatting log messages.

Parameters:

  • output_fd — output file descriptor to check

log_writer_syslog

def log_writer_syslog(log_level: LogLevelFlags | int, fields: list[LogField], user_data: int | None = ...) -> LogWriterOutput

Format a structured log message and send it to the syslog daemon. Only fields which are understood by this function are included in the formatted string which is printed.

Log facility will be defined via the SYSLOG_FACILITY field and accepts the following values: "auth", "daemon", and "user". If SYSLOG_FACILITY is not specified, LOG_USER facility will be used.

This is suitable for use as a LogWriterFunc.

If syslog is not supported, this function is still defined, but will always return LogWriterOutput.UNHANDLED.

Parameters:

  • log_level — log level, either from LogLevelFlags, or a user-defined level
  • fields — key–value pairs of structured data forming the log message
  • user_data — user data passed to log_set_writer_func

lstat

def lstat(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], buf: StatBuf) -> int

A wrapper for the POSIX lstat() function. The lstat() function is like stat() except that in the case of symbolic links, it returns information about the symbolic link itself and not the file that it refers to. If the system does not support symbolic links lstat is identical to stat.

See your C library manual for more details about lstat().

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • buf — a pointer to a stat struct, which will be filled with the file information

main_current_source

def main_current_source() -> Source | None

Returns the currently firing source for this thread.

main_depth

def main_depth() -> int

Returns the depth of the stack of calls to MainContext.dispatch on any MainContext in the current thread.

That is, when called from the top level, it gives 0. When called from within a callback from MainContext.iteration (or MainLoop.run, etc.) it returns 1. When called from within a callback to a recursive call to MainContext.iteration, it returns 2. And so forth.

This function is useful in a situation like the following: Imagine an extremely simple ‘garbage collected’ system.

static GList *free_list;

gpointer
allocate_memory (gsize size)
{
  gpointer result = g_malloc (size);
  free_list = g_list_prepend (free_list, result);
  return result;
}

void
free_allocated_memory (void)
{
  GList *l;
  for (l = free_list; l; l = l->next);
    g_free (l->data);
  g_list_free (free_list);
  free_list = NULL;
 }

[...]

while (TRUE);
 {
   g_main_context_iteration (NULL, TRUE);
   free_allocated_memory();
  }

This works from an application, however, if you want to do the same thing from a library, it gets more difficult, since you no longer control the main loop. You might think you can simply use an idle function to make the call to free_allocated_memory(), but that doesn’t work, since the idle function could be called from a recursive callback. This can be fixed by using main_depth

gpointer
allocate_memory (gsize size)
{
  FreeListBlock *block = g_new (FreeListBlock, 1);
  block->mem = g_malloc (size);
  block->depth = g_main_depth ();
  free_list = g_list_prepend (free_list, block);
  return block->mem;
}

void
free_allocated_memory (void)
{
  GList *l;

  int depth = g_main_depth ();
  for (l = free_list; l; );
    {
      GList *next = l->next;
      FreeListBlock *block = l->data;
      if (block->depth > depth)
        {
          g_free (block->mem);
          g_free (block);
          free_list = g_list_delete_link (free_list, l);
        }

      l = next;
    }
  }

There is a temptation to use main_depth to solve problems with reentrancy. For instance, while waiting for data to be received from the network in response to a menu item, the menu item might be selected again. It might seem that one could make the menu item’s callback return immediately and do nothing if main_depth returns a value greater than 1. However, this should be avoided since the user then sees selecting the menu item do nothing. Furthermore, you’ll find yourself adding these checks all over your code, since there are doubtless many, many things that the user could do. Instead, you can use the following techniques:

  1. Use gtk_widget_set_sensitive() or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.

  2. Avoid main loop recursion in situations where you can’t handle arbitrary callbacks. Instead, structure your code so that you simply return to the main loop and then get called again when there is more work to do.

malloc

def malloc(n_bytes: int) -> int | None

Allocates n_bytes bytes of memory. If n_bytes is 0 it returns None.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters:

  • n_bytes — the number of bytes to allocate

malloc0

def malloc0(n_bytes: int) -> int | None

Allocates n_bytes bytes of memory, initialized to 0's. If n_bytes is 0 it returns None.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters:

  • n_bytes — the number of bytes to allocate

malloc0_n

def malloc0_n(n_blocks: int, n_block_bytes: int) -> int | None

This function is similar to malloc0, allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters:

  • n_blocks — the number of blocks to allocate
  • n_block_bytes — the size of each block in bytes

malloc_n

def malloc_n(n_blocks: int, n_block_bytes: int) -> int | None

This function is similar to malloc, allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters:

  • n_blocks — the number of blocks to allocate
  • n_block_bytes — the size of each block in bytes

markup_error_quark

def markup_error_quark() -> Quark

markup_escape_text

def markup_escape_text(text: str, length: int) -> str

Escapes text so that the markup parser will parse it verbatim. Less than, greater than, ampersand, etc. are replaced with the corresponding entities. This function would typically be used when writing out a file to be parsed with the markup parser.

Note that this function doesn't protect whitespace and line endings from being processed according to the XML rules for normalization of line endings and attribute values.

Note also that this function will produce character references in the range of  ...  for all control sequences except for tabstop, newline and carriage return. The character references in this range are not valid XML 1.0, but they are valid XML 1.1 and will be accepted by the GMarkup parser.

Parameters:

  • text — some valid UTF-8 text
  • length — length of text in bytes, or -1 if the text is nul-terminated

mem_is_system_malloc

def mem_is_system_malloc() -> bool

:::warning Deprecated since 2.46 This API is deprecated. :::

Checks whether the allocator used by malloc is the system's malloc implementation. If it returns True memory allocated with malloc() can be used interchangeably with memory allocated using malloc. This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.

mem_profile

def mem_profile() -> None

:::warning Deprecated since 2.46 This API is deprecated. :::

GLib used to support some tools for memory profiling, but this no longer works. There are many other useful tools for memory profiling these days which can be used instead.

mem_set_vtable

def mem_set_vtable(vtable: MemVTable) -> None

:::warning Deprecated since 2.46 This API is deprecated. :::

This function used to let you override the memory allocation function. However, its use was incompatible with the use of global constructors in GLib and GIO, because those use the GLib allocators before main is reached. Therefore this function is now deprecated and is just a stub.

Parameters:

  • vtable — table of memory allocation routines.

memdup

def memdup(mem: int | None, byte_size: int) -> int | None

:::warning Deprecated since 2.68 This API is deprecated. :::

Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem. If mem is NULL it returns NULL.

Parameters:

  • mem — the memory to copy
  • byte_size — the number of bytes to copy

memdup2

def memdup2(mem: int | None, byte_size: int) -> int | None

Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem. If mem is NULL it returns NULL.

This replaces memdup, which was prone to integer overflows when converting the argument from a gsize to a guint.

Parameters:

  • mem — the memory to copy
  • byte_size — the number of bytes to copy

mkdir

def mkdir(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: int) -> int

A wrapper for the POSIX mkdir() function. The mkdir() function attempts to create a directory with the given name and permissions. The mode argument is ignored on Windows.

See your C library manual for more details about mkdir().

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • mode — permissions to use for the newly created directory

mkdir_with_parents

def mkdir_with_parents(pathname: str | bytes | os.PathLike[str] | os.PathLike[bytes], mode: int) -> int

Create a directory if it doesn't already exist. Create intermediate parent directories as needed, too.

Parameters:

  • pathname — a pathname in the GLib file name encoding
  • mode — permissions to use for newly created directories

nullify_pointer

def nullify_pointer(nullify_location: int) -> None

Set the pointer at the specified location to None.

Parameters:

  • nullify_location — the memory address of the pointer.

number_parser_error_quark

def number_parser_error_quark() -> Quark

on_error_query

def on_error_query(prg_name: str) -> None

Prompts the user with [E]xit, [H]alt, show [S]tack trace or [P]roceed. This function is intended to be used for debugging use only. The following example shows how it can be used together with the g_log() functions.

#include <glib.h>

static void
log_handler (const gchar   *log_domain,
             GLogLevelFlags log_level,
             const gchar   *message,
             gpointer       user_data)
{
  g_log_default_handler (log_domain, log_level, message, user_data);

  g_on_error_query (MY_PROGRAM_NAME);
}

int
main (int argc, char *argv[])
{
  g_log_set_handler (MY_LOG_DOMAIN,
                     G_LOG_LEVEL_WARNING |
                     G_LOG_LEVEL_ERROR |
                     G_LOG_LEVEL_CRITICAL,
                     log_handler,
                     NULL);
  ...

If "[E]xit" is selected, the application terminates with a call to _exit(0).

If "[S]tack" trace is selected, on_error_stack_trace is called. This invokes gdb, which attaches to the current process and shows a stack trace. The prompt is then shown again.

If "[P]roceed" is selected, the function returns.

This function may cause different actions on non-UNIX platforms.

On Windows consider using the G_DEBUGGER environment variable (see Running GLib Applications) and calling on_error_stack_trace instead.

Parameters:

  • prg_name — the program name, needed by gdb for the "[S]tack trace" option. If prg_name is None, get_prgname is called to get the program name (which will work correctly if gdk_init() or Gtk.init has been called)

on_error_stack_trace

def on_error_stack_trace(prg_name: str | None = ...) -> None

Invokes gdb, which attaches to the current process and shows a stack trace. Called by on_error_query when the "[S]tack trace" option is selected. You can get the current process's program name with get_prgname, assuming that you have called Gtk.init or gdk_init().

This function may cause different actions on non-UNIX platforms.

When running on Windows, this function is not called by on_error_query. If called directly, it will raise an exception, which will crash the program. If the G_DEBUGGER environment variable is set, a debugger will be invoked to attach and handle that exception (see Running GLib Applications).

Parameters:

  • prg_name — the program name, needed by gdb for the "[S]tack trace" option, or NULL to use a default string

open

def open(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], flags: int, mode: int) -> int

A wrapper for the POSIX open() function. The open() function is used to convert a pathname into a file descriptor.

On POSIX systems file descriptors are implemented by the operating system. On Windows, it's the C library that implements open() and file descriptors. The actual Win32 API for opening files is quite different, see MSDN documentation for CreateFile(). The Win32 API uses file handles, which are more randomish integers, not small integers like file descriptors.

Because file descriptors are specific to the C library on Windows, the file descriptor returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the file descriptor returned by this function cannot be passed to C library functions like write() or read().

See your C library manual for more details about open().

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • flags — as in open()
  • mode — as in open()

option_error_quark

def option_error_quark() -> Quark

parse_debug_string

def parse_debug_string(string: str | None, keys: list[DebugKey]) -> int

Parses a string containing debugging options into a guint containing bit flags. This is used within GDK and GTK to parse the debug options passed on the command line or through environment variables.

If string is equal to "all", all flags are set. Any flags specified along with "all" in string are inverted; thus, "all,foo,bar" or "foo,bar,all" sets all flags except those corresponding to "foo" and "bar".

If string is equal to "help", all the available keys in keys are printed out to standard error.

Parameters:

  • string — a list of debug options separated by colons, spaces, or commas, or None.
  • keys — pointer to an array of DebugKey which associate strings with bit flags.

path_get_basename

def path_get_basename(file_name: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str

Gets the last component of the filename.

If file_name ends with a directory separator it gets the component before the last slash. If file_name consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If file_name is empty, it gets ".".

Parameters:

  • file_name — the name of the file

path_get_dirname

def path_get_dirname(file_name: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str

Gets the directory components of a file name. For example, the directory component of /usr/bin/test is /usr/bin. The directory component of / is /.

If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

Parameters:

  • file_name — the name of the file

path_is_absolute

def path_is_absolute(file_name: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> bool

Returns True if the given file_name is an absolute file name. Note that this is a somewhat vague concept on Windows.

On POSIX systems, an absolute file name is well-defined. It always starts from the single root directory. For example "/usr/local".

On Windows, the concepts of current drive and drive-specific current directory introduce vagueness. This function interprets as an absolute file name one that either begins with a directory separator such as "\Users\tml" or begins with the root on a drive, for example "C:\Windows". The first case also includes UNC paths such as "\\myserver\docs\foo". In all cases, either slashes or backslashes are accepted.

Note that a file name relative to the current drive root does not truly specify a file uniquely over time and across processes, as the current drive is a per-process value and can be changed.

File names relative the current directory on some specific drive, such as "D:foo/bar", are not interpreted as absolute by this function, but they obviously are not relative to the normal current directory as returned by getcwd() or get_current_dir either. Such paths should be avoided, or need to be handled using Windows-specific code.

Parameters:

  • file_name — a file name

path_skip_root

def path_skip_root(file_name: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str | None

Returns a pointer into file_name after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If file_name is not an absolute path it returns None.

Parameters:

  • file_name — a file name

pattern_match_simple

def pattern_match_simple(pattern: str, string: str) -> bool

Matches a string against a pattern given as a string.

If this function is to be called in a loop, it’s more efficient to compile the pattern once with PatternSpec.new and call PatternSpec.match_string repeatedly.

Parameters:

  • pattern — the UTF-8 encoded pattern
  • string — the UTF-8 encoded string to match

pointer_bit_lock

def pointer_bit_lock(address: int, lock_bit: int) -> None

This is equivalent to bit_lock, but working on pointers (or other pointer-sized values).

For portability reasons, you may only lock on the bottom 32 bits of the pointer.

While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

Parameters:

  • address — a pointer to a #gpointer-sized value
  • lock_bit — a bit value between 0 and 31

pointer_bit_lock_and_get

def pointer_bit_lock_and_get(address: int, lock_bit: int) -> int

This is equivalent to bit_lock, but working on pointers (or other pointer-sized values).

For portability reasons, you may only lock on the bottom 32 bits of the pointer.

Parameters:

  • address — a pointer to a #gpointer-sized value
  • lock_bit — a bit value between 0 and 31

pointer_bit_lock_mask_ptr

def pointer_bit_lock_mask_ptr(ptr: int | None, lock_bit: int, set: bool, preserve_mask: int, preserve_ptr: int | None = ...) -> int | None

This mangles ptr as pointer_bit_lock and pointer_bit_unlock do.

Parameters:

  • ptr — the pointer to mask
  • lock_bit — the bit to set/clear. If set to G_MAXUINT, the lockbit is taken from preserve_ptr or ptr (depending on preserve_mask).
  • set — whether to set (lock) the bit or unset (unlock). This has no effect, if lock_bit is set to G_MAXUINT.
  • preserve_mask — if non-zero, a bit-mask for preserve_ptr. The preserve_mask bits from preserve_ptr are set in the result. Note that the lock_bit bit will be always set according to set, regardless of preserve_mask and preserve_ptr (unless lock_bit is G_MAXUINT).
  • preserve_ptr — if preserve_mask is non-zero, the bits from this pointer are set in the result.

pointer_bit_trylock

def pointer_bit_trylock(address: int, lock_bit: int) -> bool

This is equivalent to bit_trylock, but working on pointers (or other pointer-sized values).

For portability reasons, you may only lock on the bottom 32 bits of the pointer.

While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

Parameters:

  • address — a pointer to a #gpointer-sized value
  • lock_bit — a bit value between 0 and 31

pointer_bit_unlock

def pointer_bit_unlock(address: int, lock_bit: int) -> None

This is equivalent to bit_unlock, but working on pointers (or other pointer-sized values).

For portability reasons, you may only lock on the bottom 32 bits of the pointer.

While address has a volatile qualifier, this is a historical artifact and the argument passed to it should not be volatile.

Parameters:

  • address — a pointer to a #gpointer-sized value
  • lock_bit — a bit value between 0 and 31

pointer_bit_unlock_and_set

def pointer_bit_unlock_and_set(address: int, lock_bit: int, ptr: int | None, preserve_mask: int) -> None

This is equivalent to pointer_bit_unlock and atomically setting the pointer value.

Note that the lock bit will be cleared from the pointer. If the unlocked pointer that was set is not identical to ptr, an assertion fails. In other words, ptr must have lock_bit unset. This also means, you usually can only use this on the lowest bits.

Parameters:

  • address — a pointer to a #gpointer-sized value
  • lock_bit — a bit value between 0 and 31
  • ptr — the new pointer value to set
  • preserve_mask — if non-zero, those bits of the current pointer in address are preserved. Note that the lock_bit bit will be always unset regardless of ptr, preserve_mask and the currently set value in address.

poll

def poll(fds: PollFD, nfds: int, timeout: int) -> int

Polls fds, as with the poll() system call, but portably. (On systems that don't have poll(), it is emulated using select().) This is used internally by MainContext, but it can be called directly if you need to block until a file descriptor is ready, but don't want to run the full main loop.

Each element of fds is a PollFD describing a single file descriptor to poll. The fd field indicates the file descriptor, and the events field indicates the events to poll for. On return, the revents fields will be filled with the events that actually occurred.

On POSIX systems, the file descriptors in fds can be any sort of file descriptor, but the situation is much more complicated on Windows. If you need to use poll in code that has to run on Windows, the easiest solution is to construct all of your GPollFDs with g_io_channel_win32_make_pollfd().

Parameters:

  • fds — file descriptors to poll
  • nfds — the number of file descriptors in fds
  • timeout — amount of time to wait, in milliseconds, or -1 to wait forever

prefix_error_literal

def prefix_error_literal(err: Error, prefix: str) -> Error

Prefixes prefix to an existing error message. If err or *err is None (i.e.: no error variable) then do nothing.

Parameters:

  • err — a return location for a Error, or None
  • prefix — string to prefix err with

propagate_error

def propagate_error(src: Error) -> Error

If dest is None, free src; otherwise, moves src into *dest. The error variable dest points to must be None.

src must be non-None.

Note that src is no longer valid after this call. If you want to keep using the same GError*, you need to set it to None after calling this function on it.

Parameters:

  • src — error to move into the return location

qsort_with_data

def qsort_with_data(pbase: int, total_elems: int, size: int, compare_func: CompareDataFunc) -> None

:::warning Deprecated since 2.82 This API is deprecated. :::

This is just like the standard C qsort() function, but the comparison routine accepts a user data argument (like qsort_r()).

Unlike qsort(), this is guaranteed to be a stable sort (since GLib 2.32).

Parameters:

  • pbase — start of array to sort
  • total_elems — elements in the array
  • size — size of each element
  • compare_func — function to compare elements

quark_from_static_string

def quark_from_static_string(string: str | None = ...) -> Quark

Gets the GQuark identifying the given (static) string. If the string does not currently have an associated GQuark, a new GQuark is created, linked to the given string.

Note that this function is identical to quark_from_string except that if a new GQuark is created the string itself is used rather than a copy. This saves memory, but can only be used if the string will continue to exist until the program terminates. It can be used with statically allocated strings in the main program, but not with statically allocated memory in dynamically loaded modules, if you expect to ever unload the module again (e.g. do not use this function in GTK theme engines).

This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

Parameters:

  • string — a string

quark_from_string

def quark_from_string(string: str | None = ...) -> Quark

Gets the GQuark identifying the given string. If the string does not currently have an associated GQuark, a new GQuark is created, using a copy of the string.

This function must not be used before library constructors have finished running. In particular, this means it cannot be used to initialize global variables in C++.

Parameters:

  • string — a string

quark_to_string

def quark_to_string(quark: Quark) -> str

Gets the string associated with the given GQuark.

Parameters:

  • quark — a GQuark.

quark_try_string

def quark_try_string(string: str | None = ...) -> Quark

Gets the GQuark associated with the given string, or 0 if string is None or it has no associated GQuark.

If you want the GQuark to be created if it doesn't already exist, use quark_from_string or quark_from_static_string.

This function must not be used before library constructors have finished running.

Parameters:

  • string — a string

random_double

def random_double() -> float

Returns a random #gdouble equally distributed over the range [0..1).

random_double_range

def random_double_range(begin: float, end: float) -> float

Returns a random #gdouble equally distributed over the range [begin..end).

Parameters:

  • begin — lower closed bound of the interval
  • end — upper open bound of the interval

random_int

def random_int() -> int

Return a random #guint32 equally distributed over the range [0..2^32-1].

random_int_range

def random_int_range(begin: int, end: int) -> int

Returns a random #gint32 equally distributed over the range [begin..end-1].

Parameters:

  • begin — lower closed bound of the interval
  • end — upper open bound of the interval

random_set_seed

def random_set_seed(seed: int) -> None

Sets the seed for the global random number generator, which is used by the g_random_* functions, to seed.

Parameters:

  • seed — a value to reinitialize the global random number generator

rc_box_acquire

def rc_box_acquire(mem_block: int) -> int

Acquires a reference on the data pointed by mem_block.

Parameters:

  • mem_block — a pointer to reference counted data

rc_box_alloc

def rc_box_alloc(block_size: int) -> int

Allocates block_size bytes of memory, and adds reference counting semantics to it.

The data will be freed when its reference count drops to zero.

The allocated data is guaranteed to be suitably aligned for any built-in type.

Parameters:

  • block_size — the size of the allocation, must be greater than 0

rc_box_alloc0

def rc_box_alloc0(block_size: int) -> int

Allocates block_size bytes of memory, and adds reference counting semantics to it.

The contents of the returned data is set to zero.

The data will be freed when its reference count drops to zero.

The allocated data is guaranteed to be suitably aligned for any built-in type.

Parameters:

  • block_size — the size of the allocation, must be greater than 0

rc_box_dup

def rc_box_dup(block_size: int, mem_block: int) -> int

Allocates a new block of data with reference counting semantics, and copies block_size bytes of mem_block into it.

Parameters:

  • block_size — the number of bytes to copy, must be greater than 0
  • mem_block — the memory to copy

rc_box_get_size

def rc_box_get_size(mem_block: int) -> int

Retrieves the size of the reference counted data pointed by mem_block.

Parameters:

  • mem_block — a pointer to reference counted data

rc_box_release

def rc_box_release(mem_block: int) -> None

Releases a reference on the data pointed by mem_block.

If the reference was the last one, it will free the resources allocated for mem_block.

Parameters:

  • mem_block — a pointer to reference counted data

rc_box_release_full

def rc_box_release_full(mem_block: int, clear_func: DestroyNotify) -> None

Releases a reference on the data pointed by mem_block.

If the reference was the last one, it will call clear_func to clear the contents of mem_block, and then will free the resources allocated for mem_block.

Parameters:

  • mem_block — a pointer to reference counted data
  • clear_func — a function to call when clearing the data

realloc

def realloc(mem: int | None, n_bytes: int) -> int | None

Reallocates the memory pointed to by mem, so that it now has space for n_bytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be None, in which case it's considered to have zero-length. n_bytes may be 0, in which case None will be returned and mem will be freed unless it is None.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters:

  • mem — the memory to reallocate
  • n_bytes — new size of the memory in bytes

realloc_n

def realloc_n(mem: int | None, n_blocks: int, n_block_bytes: int) -> int | None

This function is similar to realloc, allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters:

  • mem — the memory to reallocate
  • n_blocks — the number of blocks to allocate
  • n_block_bytes — the size of each block in bytes

ref_count_compare

def ref_count_compare(rc: int, val: int) -> bool

Compares the current value of rc with val.

Parameters:

  • rc — the address of a reference count variable
  • val — the value to compare

ref_count_dec

def ref_count_dec(rc: int) -> tuple[bool, int]

Decreases the reference count.

If True is returned, the reference count reached 0. After this point, rc is an undefined state and must be reinitialized with ref_count_init to be used again.

Parameters:

  • rc — the address of a reference count variable

ref_count_inc

def ref_count_inc(rc: int) -> int

Increases the reference count.

Parameters:

  • rc — the address of a reference count variable

ref_count_init

def ref_count_init() -> int

Initializes a reference count variable to 1.

ref_string_acquire

def ref_string_acquire(str: str) -> str

Acquires a reference on a string.

Parameters:

  • str — a reference counted string

ref_string_equal

def ref_string_equal(str1: str, str2: str) -> bool

Compares two ref-counted strings for byte-by-byte equality.

It can be passed to HashTable.new as the key equality function, and behaves exactly the same as str_equal (or strcmp()), but can return slightly faster as it can check the string lengths before checking all the bytes.

Parameters:

  • str1 — a reference counted string
  • str2 — a reference counted string

ref_string_length

def ref_string_length(str: str) -> int

Retrieves the length of str.

Parameters:

  • str — a reference counted string

ref_string_new

def ref_string_new(str: str) -> str

Creates a new reference counted string and copies the contents of str into it.

Parameters:

  • str — a NUL-terminated string

ref_string_new_intern

def ref_string_new_intern(str: str) -> str

Creates a new reference counted string and copies the content of str into it.

If you call this function multiple times with the same str, or with the same contents of str, it will return a new reference, instead of creating a new string.

Parameters:

  • str — a NUL-terminated string

ref_string_new_len

def ref_string_new_len(str: str, len: int) -> str

Creates a new reference counted string and copies the contents of str into it, up to len bytes.

Since this function does not stop at nul bytes, it is the caller's responsibility to ensure that str has at least len addressable bytes.

Parameters:

  • str — a string
  • len — length of str to use, or -1 if str is nul-terminated

ref_string_release

def ref_string_release(str: str) -> None

Releases a reference on a string; if it was the last reference, the resources allocated by the string are freed as well.

Parameters:

  • str — a reference counted string

reload_user_special_dirs_cache

def reload_user_special_dirs_cache() -> None

Resets the cache used for get_user_special_dir, so that the latest on-disk version is used. Call this only if you just changed the data on disk yourself.

Due to thread safety issues this may cause leaking of strings that were previously returned from get_user_special_dir that can't be freed. We ensure to only leak the data for the directories that actually changed value though.

remove

def remove(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> int

A wrapper for the POSIX remove() function. The remove() function deletes a name from the filesystem.

See your C library manual for more details about how remove() works on your system. On Unix, remove() removes also directories, as it calls unlink() for files and rmdir() for directories. On Windows, although remove() in the C library only works for files, this function tries first remove() and then if that fails rmdir(), and thus works for both files and directories. Note however, that on Windows, it is in general not possible to remove a file that is open to some process, or mapped into memory.

If this function fails on Windows you can't infer too much from the errno value. rmdir() is tried regardless of what caused remove() to fail. Any errno value set by remove() will be overwritten by that set by rmdir().

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)

rename

def rename(oldfilename: str | bytes | os.PathLike[str] | os.PathLike[bytes], newfilename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> int

A wrapper for the POSIX rename() function. The rename() function renames a file, moving it between directories if required.

See your C library manual for more details about how rename() works on your system. It is not possible in general on Windows to rename a file that is open to some process.

Parameters:

  • oldfilename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • newfilename — a pathname in the GLib file name encoding

rmdir

def rmdir(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> int

A wrapper for the POSIX rmdir() function. The rmdir() function deletes a directory from the filesystem.

See your C library manual for more details about how rmdir() works on your system.

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)

set_application_name

def set_application_name(application_name: str) -> None

Sets a human-readable name for the application. This name should be localized if possible, and is intended for display to the user. Contrast with set_prgname, which sets a non-localized name. set_prgname will be called automatically by Gtk.init, but set_application_name will not.

Note that for thread safety reasons, this function can only be called once.

The application name will be used in contexts such as error messages, or when displaying an application's name in the task list.

Parameters:

  • application_name — localized name of the application

set_error_literal

def set_error_literal(domain: Quark, code: int, message: str) -> Error

Does nothing if err is None; if err is non-None, then *err must be None. A new Error is created and assigned to *err. Unlike g_set_error(), message is not a printf()-style format string. Use this function if message contains text you don't have control over, that could include printf() escape sequences.

Parameters:

  • domain — error domain
  • code — error code
  • message — error message

set_prgname

def set_prgname(prgname: str) -> None

Sets the name of the program. This name should not be localized, in contrast to set_application_name.

If you are using Gio.Application the program name is set in Gio.Application.run. In case of GDK or GTK it is set in gdk_init(), which is called by Gtk.init and the Gtk.Application::startup handler. By default, the program name is found by taking the last component of argv[0].

Since GLib 2.72, this function can be called multiple times and is fully thread safe. Prior to GLib 2.72, this function could only be called once per process.

See the GTK documentation for requirements on integrating set_prgname with GTK applications.

Parameters:

  • prgname — the name of the program.

setenv

def setenv(variable: str | bytes | os.PathLike[str] | os.PathLike[bytes], value: str | bytes | os.PathLike[str] | os.PathLike[bytes], overwrite: bool) -> bool

Sets an environment variable. On UNIX, both the variable's name and value can be arbitrary byte strings, except that the variable's name cannot contain '='. On Windows, they should be in UTF-8.

Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed.

You should be mindful of the fact that environment variable handling in UNIX is not thread-safe, and your program may crash if one thread calls setenv while another thread is calling getenv(). (And note that many functions, such as gettext(), call getenv() internally.) This function is only safe to use at the very start of your program, before creating any other threads (or creating objects that create worker threads of their own).

If you need to set up the environment for a child process, you can use get_environ to get an environment array, modify that with environ_setenv and environ_unsetenv, and then pass that array directly to execvpe(), spawn_async, or the like.

Parameters:

  • variable — the environment variable to set, must not contain '='.
  • value — the value for to set the variable to.
  • overwrite — whether to change the variable if it already exists.

shell_error_quark

def shell_error_quark() -> Quark

shell_parse_argv

def shell_parse_argv(command_line: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> tuple[bool, list[str]]

Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported).

The results are defined to be the same as those you would get from a UNIX98 /bin/sh, as long as the input contains none of the unsupported shell expansions. If the input does contain such expansions, they are passed through literally.

Possible errors are those from the G_SHELL_ERROR domain.

In particular, if command_line is an empty string (or a string containing only whitespace), ShellError.EMPTY_STRING will be returned. It’s guaranteed that argvp will be a non-empty array if this function returns successfully.

Free the returned vector with strfreev.

Parameters:

  • command_line — command line to parse

shell_quote

def shell_quote(unquoted_string: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str

Quotes a string so that the shell (/bin/sh) will interpret the quoted string to mean unquoted_string.

If you pass a filename to the shell, for example, you should first quote it with this function.

The return value must be freed with free.

The quoting style used is undefined (single or double quotes may be used).

Parameters:

  • unquoted_string — a literal string

shell_unquote

def shell_unquote(quoted_string: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> str

Unquotes a string as the shell (/bin/sh) would.

This function only handles quotes; if a string contains file globs, arithmetic operators, variables, backticks, redirections, or other special-to-the-shell features, the result will be different from the result a real shell would produce (the variables, backticks, etc. will be passed through literally instead of being expanded).

This function is guaranteed to succeed if applied to the result of shell_quote. If it fails, it returns None and sets the error.

The quoted_string need not actually contain quoted or escaped text; shell_unquote simply goes through the string and unquotes/unescapes anything that the shell would. Both single and double quotes are handled, as are escapes including escaped newlines.

The return value must be freed with free.

Possible errors are in the G_SHELL_ERROR domain.

Shell quoting rules are a bit strange. Single quotes preserve the literal string exactly. escape sequences are not allowed; not even \' - if you want a ' in the quoted text, you have to do something like 'foo'\''bar'. Double quotes allow $, ``,",`, and newline to be escaped with backslash. Otherwise double quotes preserve things literally.

Parameters:

  • quoted_string — shell-quoted string

slice_alloc

def slice_alloc(block_size: int) -> int | None

Allocates a block of memory from the libc allocator.

The block address handed out can be expected to be aligned to at least 1 * sizeof (void*).

Since GLib 2.76 this always uses the system malloc() implementation internally.

Parameters:

  • block_size — the number of bytes to allocate

slice_alloc0

def slice_alloc0(block_size: int) -> int | None

Allocates a block of memory via slice_alloc and initializes the returned memory to 0.

Since GLib 2.76 this always uses the system malloc() implementation internally.

Parameters:

  • block_size — the number of bytes to allocate

slice_copy

def slice_copy(block_size: int, mem_block: int | None = ...) -> int | None

Allocates a block of memory from the slice allocator and copies block_size bytes into it from mem_block.

mem_block must be non-None if block_size is non-zero.

Since GLib 2.76 this always uses the system malloc() implementation internally.

Parameters:

  • block_size — the number of bytes to allocate
  • mem_block — the memory to copy

slice_free1

def slice_free1(block_size: int, mem_block: int | None = ...) -> None

Frees a block of memory.

The memory must have been allocated via slice_alloc or slice_alloc0 and the block_size has to match the size specified upon allocation. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

If mem_block is None, this function does nothing.

Since GLib 2.76 this always uses the system free_sized() implementation internally.

Parameters:

  • block_size — the size of the block
  • mem_block — a pointer to the block to free

slice_free_chain_with_offset

def slice_free_chain_with_offset(block_size: int, mem_chain: int | None, next_offset: int) -> None

Frees a linked list of memory blocks of structure type type.

The memory blocks must be equal-sized, allocated via slice_alloc or slice_alloc0 and linked together by a next pointer (similar to SList). The offset of the next field in each block is passed as third argument. Note that the exact release behaviour can be changed with the G_DEBUG=gc-friendly environment variable.

If mem_chain is None, this function does nothing.

Since GLib 2.76 this always uses the system free_sized() implementation internally.

Parameters:

  • block_size — the size of the blocks
  • mem_chain — a pointer to the first block of the chain
  • next_offset — the offset of the next field in the blocks

slice_get_config

def slice_get_config(ckey: SliceConfig | int) -> int

slice_get_config_state

def slice_get_config_state(ckey: SliceConfig | int, address: int, n_values: int) -> int

slice_set_config

def slice_set_config(ckey: SliceConfig | int, value: int) -> None

spaced_primes_closest

def spaced_primes_closest(num: int) -> int

Gets the smallest prime number from a built-in array of primes which is larger than num. This is used within GLib to calculate the optimum size of a HashTable.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

Parameters:

  • num — a #guint

spawn_async

def spawn_async(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None = ...) -> tuple[bool, Pid]

Executes a child program asynchronously.

See spawn_async_with_pipes_and_fds for a full description; this function simply calls the spawn_async_with_pipes without any pipes, which in turn calls spawn_async_with_pipes_and_fds.

You should call spawn_close_pid on the returned child process reference when you don't need it any more.

If you are writing a GTK application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use Gdk.AppLaunchContext, Gio.AppLaunchContext, or set the DISPLAY environment variable.

Note that the returned child_pid on Windows is a handle to the child process and not its identifier. Process handles and process identifiers are different concepts on Windows.

Parameters:

  • working_directory — child's current working directory, or None to inherit parent's
  • argv — child's argument vector
  • envp — child's environment, or None to inherit parent's
  • flags — flags from SpawnFlags
  • child_setup — function to run in the child just before exec()

spawn_async_with_fds

def spawn_async_with_fds(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str], envp: list[str] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None, stdin_fd: int, stdout_fd: int, stderr_fd: int) -> tuple[bool, Pid]

Executes a child program asynchronously.

Identical to spawn_async_with_pipes_and_fds but with n_fds set to zero, so no FD assignments are used.

Parameters:

  • working_directory — child's current working directory, or None to inherit parent's, in the GLib file name encoding
  • argv — child's argument vector, in the GLib file name encoding; it must be non-empty and None-terminated
  • envp — child's environment, or None to inherit parent's, in the GLib file name encoding
  • flags — flags from SpawnFlags
  • child_setup — function to run in the child just before exec()
  • stdin_fd — file descriptor to use for child's stdin, or -1
  • stdout_fd — file descriptor to use for child's stdout, or -1
  • stderr_fd — file descriptor to use for child's stderr, or -1

spawn_async_with_pipes

def spawn_async_with_pipes(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None = ...) -> tuple[bool, Pid, int, int, int]

Identical to spawn_async_with_pipes_and_fds but with n_fds set to zero, so no FD assignments are used.

Parameters:

  • working_directory — child's current working directory, or None to inherit parent's, in the GLib file name encoding
  • argv — child's argument vector, in the GLib file name encoding; it must be non-empty and None-terminated
  • envp — child's environment, or None to inherit parent's, in the GLib file name encoding
  • flags — flags from SpawnFlags
  • child_setup — function to run in the child just before exec()

spawn_async_with_pipes_and_fds

def spawn_async_with_pipes_and_fds(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None, stdin_fd: int, stdout_fd: int, stderr_fd: int, source_fds: list[int] | None = ..., target_fds: list[int] | None = ...) -> tuple[bool, Pid, int, int, int]

Executes a child program asynchronously (your program will not block waiting for the child to exit).

The child program is specified by the only argument that must be provided, argv. argv should be a None-terminated array of strings, to be passed as the argument vector for the child. The first string in argv is of course the name of the program to execute. By default, the name of the program must be a full path. If flags contains the SpawnFlags.SEARCH_PATH flag, the PATH environment variable is used to search for the executable. If flags contains the SpawnFlags.SEARCH_PATH_FROM_ENVP flag, the PATH variable from envp is used to search for the executable. If both the SpawnFlags.SEARCH_PATH and SpawnFlags.SEARCH_PATH_FROM_ENVP flags are set, the PATH variable from envp takes precedence over the environment variable.

If the program name is not a full path and SpawnFlags.SEARCH_PATH flag is not used, then the program will be run from the current directory (or working_directory, if specified); this might be unexpected or even dangerous in some cases when the current directory is world-writable.

On Windows, note that all the string or string vector arguments to this function and the other g_spawn*() functions are in UTF-8, the GLib file name encoding. Unicode characters that are not part of the system codepage passed in these arguments will be correctly available in the spawned program only if it uses wide character API to retrieve its command line. For C programs built with Microsoft's tools it is enough to make the program have a wmain() instead of main(). wmain() has a wide character argument vector as parameter.

At least currently, mingw doesn't support wmain(), so if you use mingw to develop the spawned program, it should call g_win32_get_command_line() to get arguments in UTF-8.

On Windows the low-level child process creation API CreateProcess() doesn't use argument vectors, but a command line. The C runtime library's spawn*() family of functions (which spawn_async_with_pipes eventually calls) paste the argument vector elements together into a command line, and the C runtime startup code does a corresponding reconstruction of an argument vector from the command line, to be passed to main(). Complications arise when you have argument vector elements that contain spaces or double quotes. The spawn*() functions don't do any quoting or escaping, but on the other hand the startup code does do unquoting and unescaping in order to enable receiving arguments with embedded spaces or double quotes. To work around this asymmetry, spawn_async_with_pipes will do quoting and escaping on argument vector elements that need it before calling the C runtime spawn() function.

The returned child_pid on Windows is a handle to the child process, not its identifier. Process handles and process identifiers are different concepts on Windows.

envp is a None-terminated array of strings, where each string has the form KEY=VALUE. This will become the child's environment. If envp is None, the child inherits its parent's environment.

flags should be the bitwise OR of any flags you want to affect the function's behaviour. The SpawnFlags.DO_NOT_REAP_CHILD means that the child will not automatically be reaped; you must use a child watch (g_child_watch_add()) to be notified about the death of the child process, otherwise it will stay around as a zombie process until this process exits. Eventually you must call spawn_close_pid on the child_pid, in order to free resources which may be associated with the child process. (On Unix, using a child watch is equivalent to calling waitpid() or handling the SIGCHLD signal manually. On Windows, calling spawn_close_pid is equivalent to calling CloseHandle() on the process handle returned in child_pid). See g_child_watch_add().

Open UNIX file descriptors marked as FD_CLOEXEC will be automatically closed in the child process. SpawnFlags.LEAVE_DESCRIPTORS_OPEN means that other open file descriptors will be inherited by the child; otherwise all descriptors except stdin/stdout/stderr will be closed before calling exec() in the child. SpawnFlags.SEARCH_PATH means that argv[0] need not be an absolute path, it will be looked for in the PATH environment variable. SpawnFlags.SEARCH_PATH_FROM_ENVP means need not be an absolute path, it will be looked for in the PATH variable from envp. If both SpawnFlags.SEARCH_PATH and SpawnFlags.SEARCH_PATH_FROM_ENVP are used, the value from envp takes precedence over the environment.

SpawnFlags.CHILD_INHERITS_STDIN means that the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null). SpawnFlags.STDIN_FROM_DEV_NULL explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stdin_pipe_out argument is ignored.

SpawnFlags.STDOUT_TO_DEV_NULL means that the child's standard output will be discarded (by default, it goes to the same location as the parent's standard output). SpawnFlags.CHILD_INHERITS_STDOUT explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stdout_pipe_out argument is ignored.

SpawnFlags.STDERR_TO_DEV_NULL means that the child's standard error will be discarded (by default, it goes to the same location as the parent's standard error). SpawnFlags.CHILD_INHERITS_STDERR explicitly imposes the default behavior. Both flags cannot be enabled at the same time and, in both cases, the stderr_pipe_out argument is ignored.

It is valid to pass the same FD in multiple parameters (e.g. you can pass a single FD for both stdout_fd and stderr_fd, and include it in source_fds too).

source_fds and target_fds allow zero or more FDs from this process to be remapped to different FDs in the spawned process. If n_fds is greater than zero, source_fds and target_fds must both be non-None and the same length. Each FD in source_fds is remapped to the FD number at the same index in target_fds. The source and target FD may be equal to simply propagate an FD to the spawned process. FD remappings are processed after standard FDs, so any target FDs which equal stdin_fd, stdout_fd or stderr_fd will overwrite them in the spawned process.

source_fds is supported on Windows since 2.72.

SpawnFlags.FILE_AND_ARGV_ZERO means that the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally spawn_async_with_pipes uses argv[0] as the file to execute, and passes all of argv to the child.

child_setup and user_data are a function and user data. On POSIX platforms, the function is called in the child after GLib has performed all the setup it plans to perform (including creating pipes, closing file descriptors, etc.) but before calling exec(). That is, child_setup is called just before calling exec() in the child. Obviously actions taken in this function will only affect the child, not the parent.

On Windows, there is no separate fork() and exec() functionality. Child processes are created and run with a single API call, CreateProcess(). There is no sensible thing child_setup could be used for on Windows so it is ignored and not called.

If non-None, child_pid will on Unix be filled with the child's process ID. You can use the process ID to send signals to the child, or to use g_child_watch_add() (or waitpid()) if you specified the SpawnFlags.DO_NOT_REAP_CHILD flag. On Windows, child_pid will be filled with a handle to the child process only if you specified the SpawnFlags.DO_NOT_REAP_CHILD flag. You can then access the child process using the Win32 API, for example wait for its termination with the WaitFor*() functions, or examine its exit code with GetExitCodeProcess(). You should close the handle with CloseHandle() or spawn_close_pid when you no longer need it.

If non-None, the stdin_pipe_out, stdout_pipe_out, stderr_pipe_out locations will be filled with file descriptors for writing to the child's standard input or reading from its standard output or standard error. The caller of spawn_async_with_pipes must close these file descriptors when they are no longer in use. If these parameters are None, the corresponding pipe won't be created.

If stdin_pipe_out is None, the child's standard input is attached to /dev/null unless SpawnFlags.CHILD_INHERITS_STDIN is set.

If stderr_pipe_out is NULL, the child's standard error goes to the same location as the parent's standard error unless SpawnFlags.STDERR_TO_DEV_NULL is set.

If stdout_pipe_out is NULL, the child's standard output goes to the same location as the parent's standard output unless SpawnFlags.STDOUT_TO_DEV_NULL is set.

error can be None to ignore errors, or non-None to report errors. If an error is set, the function returns False. Errors are reported even if they occur in the child (for example if the executable in @argv[0] is not found). Typically the message field of returned errors should be displayed to users. Possible errors are those from the G_SPAWN_ERROR domain.

If an error occurs, child_pid, stdin_pipe_out, stdout_pipe_out, and stderr_pipe_out will not be filled with valid values.

If child_pid is not None and an error does not occur then the returned process reference must be closed using spawn_close_pid.

On modern UNIX platforms, GLib can use an efficient process launching codepath driven internally by posix_spawn(). This has the advantage of avoiding the fork-time performance costs of cloning the parent process address space, and avoiding associated memory overcommit checks that are not relevant in the context of immediately executing a distinct process. This optimized codepath will be used provided that the following conditions are met:

  1. SpawnFlags.DO_NOT_REAP_CHILD is set
  2. SpawnFlags.LEAVE_DESCRIPTORS_OPEN is set
  3. SpawnFlags.SEARCH_PATH_FROM_ENVP is not set
  4. working_directory is None
  5. child_setup is None
  6. The program is of a recognised binary format, or has a shebang. Otherwise, GLib will have to execute the program through the shell, which is not done using the optimized codepath.

If you are writing a GTK application, and the program you are spawning is a graphical application too, then to ensure that the spawned program opens its windows on the right screen, you may want to use Gdk.AppLaunchContext, Gio.AppLaunchContext, or set the DISPLAY environment variable.

Parameters:

  • working_directory — child's current working directory, or None to inherit parent's, in the GLib file name encoding
  • argv — child's argument vector, in the GLib file name encoding; it must be non-empty and None-terminated
  • envp — child's environment, or None to inherit parent's, in the GLib file name encoding
  • flags — flags from SpawnFlags
  • child_setup — function to run in the child just before exec()
  • stdin_fd — file descriptor to use for child's stdin, or -1
  • stdout_fd — file descriptor to use for child's stdout, or -1
  • stderr_fd — file descriptor to use for child's stderr, or -1
  • source_fds — array of FDs from the parent process to make available in the child process
  • target_fds — array of FDs to remap source_fds to in the child process

spawn_check_exit_status

def spawn_check_exit_status(wait_status: int) -> bool

:::warning Deprecated since 2.70 This API is deprecated. :::

An old name for spawn_check_wait_status, deprecated because its name is misleading.

Despite the name of the function, wait_status must be the wait status as returned by spawn_sync, Gio.Subprocess.get_status, waitpid(), etc. On Unix platforms, it is incorrect for it to be the exit status as passed to exit() or returned by Gio.Subprocess.get_exit_status or WEXITSTATUS().

Parameters:

  • wait_status — A status as returned from spawn_sync

spawn_check_wait_status

def spawn_check_wait_status(wait_status: int) -> bool

Set error if wait_status indicates the child exited abnormally (e.g. with a nonzero exit code, or via a fatal signal).

The spawn_sync and g_child_watch_add() family of APIs return the status of subprocesses encoded in a platform-specific way. On Unix, this is guaranteed to be in the same format waitpid() returns, and on Windows it is guaranteed to be the result of GetExitCodeProcess().

Prior to the introduction of this function in GLib 2.34, interpreting wait_status required use of platform-specific APIs, which is problematic for software using GLib as a cross-platform layer.

Additionally, many programs simply want to determine whether or not the child exited successfully, and either propagate a Error or print a message to standard error. In that common case, this function can be used. Note that the error message in error will contain human-readable information about the wait status.

The domain and code of error have special semantics in the case where the process has an "exit code", as opposed to being killed by a signal. On Unix, this happens if WIFEXITED() would be true of wait_status. On Windows, it is always the case.

The special semantics are that the actual exit code will be the code set in error, and the domain will be G_SPAWN_EXIT_ERROR. This allows you to differentiate between different exit codes.

If the process was terminated by some means other than an exit status (for example if it was killed by a signal), the domain will be G_SPAWN_ERROR and the code will be SpawnError.FAILED.

This function just offers convenience; you can of course also check the available platform via a macro such as G_OS_UNIX, and use WIFEXITED() and WEXITSTATUS() on wait_status directly. Do not attempt to scan or parse the error message string; it may be translated and/or change in future versions of GLib.

Prior to version 2.70, spawn_check_exit_status provides the same functionality, although under a misleading name.

Parameters:

  • wait_status — A platform-specific wait status as returned from spawn_sync

spawn_close_pid

def spawn_close_pid(pid: Pid) -> None

On some platforms, notably Windows, the GPid type represents a resource which must be closed to prevent resource leaking. spawn_close_pid is provided for this purpose. It should be used on all platforms, even though it doesn't do anything under UNIX.

Parameters:

  • pid — The process reference to close

spawn_command_line_async

def spawn_command_line_async(command_line: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> bool

A simple version of spawn_async that parses a command line with shell_parse_argv and passes it to spawn_async.

Runs a command line in the background. Unlike spawn_async, the SpawnFlags.SEARCH_PATH flag is enabled, other flags are not. Note that SpawnFlags.SEARCH_PATH can have security implications, so consider using spawn_async directly if appropriate. Possible errors are those from shell_parse_argv and spawn_async.

The same concerns on Windows apply as for spawn_command_line_sync.

Parameters:

  • command_line — a command line

spawn_command_line_sync

def spawn_command_line_sync(command_line: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> tuple[bool, list[int], list[int], int]

A simple version of spawn_sync with little-used parameters removed, taking a command line instead of an argument vector.

See spawn_sync for full details.

The command_line argument will be parsed by shell_parse_argv.

Unlike spawn_sync, the SpawnFlags.SEARCH_PATH flag is enabled. Note that SpawnFlags.SEARCH_PATH can have security implications, so consider using spawn_sync directly if appropriate.

Possible errors are those from spawn_sync and those from shell_parse_argv.

If wait_status is non-None, the platform-specific status of the child is stored there; see the documentation of spawn_check_wait_status for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed to exit() or returned from main().

On Windows, please note the implications of shell_parse_argv parsing command_line. Parsing is done according to Unix shell rules, not Windows command interpreter rules. Space is a separator, and backslashes are special. Thus you cannot simply pass a command_line containing canonical Windows paths, like "c:\program files\app\app.exe", as the backslashes will be eaten, and the space will act as a separator. You need to enclose such paths with single quotes, like "'c:\program files\app\app.exe' 'e:\folder\argument.txt'".

Parameters:

  • command_line — a command line

spawn_error_quark

def spawn_error_quark() -> Quark

spawn_exit_error_quark

def spawn_exit_error_quark() -> Quark

spawn_sync

def spawn_sync(working_directory: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None, argv: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]], envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, flags: SpawnFlags | int, child_setup: SpawnChildSetupFunc | None = ...) -> tuple[bool, list[int], list[int], int]

Executes a child synchronously (waits for the child to exit before returning).

All output from the child is stored in standard_output and standard_error, if those parameters are non-None. Note that you must set the SpawnFlags.STDOUT_TO_DEV_NULL and SpawnFlags.STDERR_TO_DEV_NULL flags when passing None for standard_output and standard_error.

If wait_status is non-None, the platform-specific status of the child is stored there; see the documentation of spawn_check_wait_status for how to use and interpret this. On Unix platforms, note that it is usually not equal to the integer passed to exit() or returned from main().

Note that it is invalid to pass SpawnFlags.DO_NOT_REAP_CHILD in flags, and on POSIX platforms, the same restrictions as for child_watch_source_new apply.

If an error occurs, no data is returned in standard_output, standard_error, or wait_status.

This function calls spawn_async_with_pipes internally; see that function for full details on the other parameters and details on how these functions work on Windows.

Parameters:

  • working_directory — child's current working directory, or None to inherit parent's
  • argv — child's argument vector, which must be non-empty and None-terminated
  • envp — child's environment, or None to inherit parent's
  • flags — flags from SpawnFlags
  • child_setup — function to run in the child just before exec()

stat

def stat(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], buf: StatBuf) -> int

A wrapper for the POSIX stat() function. The stat() function returns information about a file. On Windows the stat() function in the C library checks only the FAT-style READONLY attribute and does not look at the ACL at all. Thus on Windows the protection bits in the st_mode field are a fabrication of little use.

On Windows the Microsoft C libraries have several variants of the stat struct and stat() function with names like _stat(), _stat32(), _stat32i64() and _stat64i32(). The one used here is for 32-bit code the one with 32-bit size and time fields, specifically called _stat32().

In Microsoft's compiler, by default struct stat means one with 64-bit time fields while in MinGW struct stat is the legacy one with 32-bit fields. To hopefully clear up this messs, the gstdio.h header defines a type StatBuf which is the appropriate struct type depending on the platform and/or compiler being used. On POSIX it is just struct stat, but note that even on POSIX platforms, stat() might be a macro.

See your C library manual for more details about stat().

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • buf — a pointer to a stat struct, which will be filled with the file information

stpcpy

def stpcpy(dest: str, src: str) -> str

Copies a nul-terminated string into the destination buffer, including the trailing nul byte, and returns a pointer to the trailing nul byte in dest. The return value is useful for concatenating multiple strings without having to repeatedly scan for the end.

Parameters:

  • dest — destination buffer
  • src — source string

str_equal

def str_equal(v1: int, v2: int) -> bool

Compares two strings for byte-by-byte equality and returns True if they are equal. It can be passed to g_hash_table_new() as the key_equal_func parameter, when using non-None strings as keys in a HashTable.

This function is typically used for hash table comparisons, but can be used for general purpose comparisons of non-None strings. For a None-safe string comparison function, see strcmp0.

Parameters:

  • v1 — a key
  • v2 — a key to compare with v1

str_has_prefix

def str_has_prefix(str: str, prefix: str) -> bool

Looks whether the string str begins with prefix.

Parameters:

  • str — a string to look in
  • prefix — the prefix to look for

str_has_suffix

def str_has_suffix(str: str, suffix: str) -> bool

Looks whether a string ends with suffix.

Parameters:

  • str — a string to look in
  • suffix — the suffix to look for

str_hash

def str_hash(v: int) -> int

Converts a string to a hash value.

This function implements the widely used "djb" hash apparently posted by Daniel Bernstein to comp.lang.c some time ago. The 32 bit unsigned hash value starts at 5381 and for each byte 'c' in the string, is updated: hash = hash * 33 + c. This function uses the signed value of each byte.

It can be passed to g_hash_table_new() as the hash_func parameter, when using non-None strings as keys in a HashTable.

Note that this function may not be a perfect fit for all use cases. For example, it produces some hash collisions with strings as short as 2.

Parameters:

  • v — a string key

str_is_ascii

def str_is_ascii(str: str) -> bool

Determines if a string is pure ASCII. A string is pure ASCII if it contains no bytes with the high bit set.

Parameters:

  • str — a string

str_match_string

def str_match_string(search_term: str, potential_hit: str, accept_alternates: bool) -> bool

Checks if a search conducted for search_term should match potential_hit.

This function calls str_tokenize_and_fold on both search_term and potential_hit. ASCII alternates are never taken for search_term but will be taken for potential_hit according to the value of accept_alternates.

A hit occurs when each folded token in search_term is a prefix of a folded token from potential_hit.

Depending on how you're performing the search, it will typically be faster to call g_str_tokenize_and_fold() on each string in your corpus and build an index on the returned folded tokens, then call g_str_tokenize_and_fold() on the search term and perform lookups into that index.

As some examples, searching for ‘fred’ would match the potential hit ‘Smith, Fred’ and also ‘Frédéric’. Searching for ‘Fréd’ would match ‘Frédéric’ but not ‘Frederic’ (due to the one-directional nature of accent matching). Searching ‘fo’ would match ‘Foo’ and ‘Bar Foo Baz’, but not ‘SFO’ (because no word has ‘fo’ as a prefix).

Parameters:

  • search_term — the search term from the user
  • potential_hit — the text that may be a hit
  • accept_alternates — if true, ASCII alternates are accepted

str_to_ascii

def str_to_ascii(str: str, from_locale: str | None = ...) -> str

Transliterate str to plain ASCII.

For best results, str should be in composed normalised form.

This function performs a reasonably good set of character replacements. The particular set of replacements that is done may change by version or even by runtime environment.

If the source language of str is known, it can used to improve the accuracy of the translation by passing it as from_locale. It should be a valid POSIX locale string (of the form language[_territory][.codeset][@modifier]).

If from_locale is None then the current locale is used.

If you want to do translation for no specific locale, and you want it to be done independently of the currently locale, specify "C" for from_locale.

Parameters:

  • str — a string, in UTF-8
  • from_locale — the source locale, if known

str_tokenize_and_fold

def str_tokenize_and_fold(string: str, translit_locale: str | None = ...) -> tuple[list[str], list[str]]

Tokenizes string and performs folding on each token.

A token is a non-empty sequence of alphanumeric characters in the source string, separated by non-alphanumeric characters. An "alphanumeric" character for this purpose is one that matches unichar_isalnum or unichar_ismark.

Each token is then (Unicode) normalised and case-folded. If ascii_alternates is non-NULL and some of the returned tokens contain non-ASCII characters, ASCII alternatives will be generated.

The number of ASCII alternatives that are generated and the method for doing so is unspecified, but translit_locale (if specified) may improve the transliteration if the language of the source string is known.

Parameters:

  • string — a string to tokenize
  • translit_locale — the language code (like 'de' or 'en_GB') from which string originates

strcanon

def strcanon(string: str, valid_chars: str, substitutor: int) -> str

For each character in string, if the character is not in valid_chars, replaces the character with substitutor.

Modifies string in place, and return string itself, not a copy. The return value is to allow nesting such as:

g_ascii_strup (g_strcanon (str, "abc", '?'))

In order to modify a copy, you may use strdup:

reformatted = g_strcanon (g_strdup (const_str), "abc", '?');

g_free (reformatted);

Parameters:

  • string — a nul-terminated array of bytes
  • valid_chars — bytes permitted in string
  • substitutor — replacement character for disallowed bytes

strcasecmp

def strcasecmp(s1: str, s2: str) -> int

:::warning Deprecated since 2.2 This API is deprecated. :::

A case-insensitive string comparison, corresponding to the standard strcasecmp() function on platforms which support it.

Parameters:

  • s1 — string to compare with s2
  • s2 — string to compare with s1

strchomp

def strchomp(string: str) -> str

Removes trailing whitespace from a string.

This function doesn't allocate or reallocate any memory; it modifies string in place. Therefore, it cannot be used on statically allocated strings.

The pointer to string is returned to allow the nesting of functions.

Also see strchug and GLib.strstrip.

Parameters:

  • string — a string to remove the trailing whitespace from

strchug

def strchug(string: str) -> str

Removes leading whitespace from a string, by moving the rest of the characters forward.

This function doesn't allocate or reallocate any memory; it modifies string in place. Therefore, it cannot be used on statically allocated strings.

The pointer to string is returned to allow the nesting of functions.

Also see strchomp and GLib.strstrip.

Parameters:

  • string — a string to remove the leading whitespace from

strcmp0

def strcmp0(str1: str | None = ..., str2: str | None = ...) -> int

Compares str1 and str2 like strcmp().

Handles NULL gracefully by sorting it before non-NULL strings. Comparing two NULL pointers returns 0.

Parameters:

  • str1 — a string
  • str2 — another string

strcompress

def strcompress(source: str) -> str

Makes a copy of a string replacing C string-style escape sequences with their one byte equivalent:

strescape does the reverse conversion.

Parameters:

  • source — a string to compress

strdelimit

def strdelimit(string: str, delimiters: str | None, new_delimiter: int) -> str

Converts any delimiter characters in string to new_delimiter.

Any characters in string which are found in delimiters are changed to the new_delimiter character. Modifies string in place, and returns string itself, not a copy.

The return value is to allow nesting such as:

g_ascii_strup (g_strdelimit (str, "abc", '?'))

In order to modify a copy, you may use strdup:

reformatted = g_strdelimit (g_strdup (const_str), "abc", '?');

g_free (reformatted);

Parameters:

  • string — the string to convert
  • delimiters — a string containing the current delimiters, or NULL to use the standard delimiters defined in STR_DELIMITERS
  • new_delimiter — the new delimiter character

strdown

def strdown(string: str) -> str

:::warning Deprecated since 2.2 This API is deprecated. :::

Converts a string to lower case.

Parameters:

  • string — the string to convert

strdup

def strdup(str: str | None = ...) -> str

Duplicates a string. If str is NULL it returns NULL.

Parameters:

  • str — the string to duplicate

strdupv

def strdupv(str_array: list[str] | None = ...) -> list[str] | None

Copies an array of strings. The copy is a deep copy; each string is also copied.

If called on a NULL value, g_strdupv() simply returns NULL.

Parameters:

  • str_array — an array of strings to copy

strerror

def strerror(errnum: int) -> str

Returns a string corresponding to the given error code, e.g. "no such process".

Unlike strerror(), this always returns a string in UTF-8 encoding, and the pointer is guaranteed to remain valid for the lifetime of the process. If the error code is unknown, it returns a string like “Unknown error <code>”.

Note that the string may be translated according to the current locale.

The value of errno will not be changed by this function. However, it may be changed by intermediate function calls, so you should save its value as soon as the call returns:

int saved_errno;

ret = read (blah);
saved_errno = errno;

g_strerror (saved_errno);

Parameters:

  • errnum — the system error number. See the standard C errno documentation

strescape

def strescape(source: str, exceptions: str | None = ...) -> str

It replaces the following special characters in the string source with their corresponding C escape sequence:

Symbol Escape
U+0008 Backspace \b
U+000C Form Feed \f
U+000A Line Feed \n
U+000D Carriage Return \r
U+0009 Horizontal Tabulation \t
U+000B Vertical Tabulation \v

It also inserts a backslash (\) before any backslash or a double quote ("). Additionally all characters in the range 0x01-0x1F (everything below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are replaced with a backslash followed by their octal representation. Characters supplied in exceptions are not escaped.

strcompress does the reverse conversion.

Parameters:

  • source — a string to escape
  • exceptions — a string of characters not to escape in source

strfreev

def strfreev(str_array: list[str] | None = ...) -> None

Frees an array of strings, as well as each string it contains.

If str_array is NULL, this function simply returns.

Parameters:

  • str_array — an array of strings to free

strip_context

def strip_context(msgid: str, msgval: str) -> str

An auxiliary function for gettext() support (see Q_()).

Parameters:

  • msgid — a string
  • msgval — another string

strjoinv

def strjoinv(separator: str | None, str_array: list[str]) -> str

Joins an array of strings together to form one long string, with the optional separator inserted between each of them.

If str_array has no items, the return value will be an empty string. If str_array contains a single item, separator will not appear in the resulting string.

Parameters:

  • separator — a string to insert between each of the strings
  • str_array — an array of strings to join

strlcat

def strlcat(dest: str, src: str, dest_size: int) -> int

Portability wrapper that calls strlcat() on systems which have it, and emulates it otherwise. Appends nul-terminated src string to dest, guaranteeing nul-termination for dest. The total size of dest won't exceed dest_size.

At most dest_size - 1 characters will be copied. Unlike strncat(), dest_size is the full size of dest, not the space left over. This function does not allocate memory. It always nul-terminates (unless dest_size == 0 or there were no nul characters in the dest_size characters of dest to start with).

Caveat: this is supposedly a more secure alternative to strcat() or strncat(), but for real security GLib.strconcat is harder to mess up.

Parameters:

  • dest — destination buffer, already containing one nul-terminated string
  • src — source buffer
  • dest_size — length of dest buffer in bytes (not length of existing string inside dest)

strlcpy

def strlcpy(dest: str, src: str, dest_size: int) -> int

Portability wrapper that calls strlcpy() on systems which have it, and emulates strlcpy() otherwise. Copies src to dest; dest is guaranteed to be nul-terminated; src must be nul-terminated; dest_size is the buffer size, not the number of bytes to copy.

At most dest_size - 1 characters will be copied. Always nul-terminates (unless dest_size is 0). This function does not allocate memory. Unlike strncpy(), this function doesn't pad dest (so it's often faster). It returns the size of the attempted result, strlen (src), so if retval >= dest_size, truncation occurred.

Caveat: strlcpy() is supposedly more secure than strcpy() or strncpy(), but if you really want to avoid screwups, strdup is an even better idea.

Parameters:

  • dest — destination buffer
  • src — source buffer
  • dest_size — length of dest in bytes

strncasecmp

def strncasecmp(s1: str, s2: str, n: int) -> int

:::warning Deprecated since 2.2 This API is deprecated. :::

A case-insensitive string comparison, corresponding to the standard strncasecmp() function on platforms which support it. It is similar to strcasecmp except it only compares the first n characters of the strings.

Parameters:

  • s1 — string to compare with s2
  • s2 — string to compare with s1
  • n — the maximum number of characters to compare

strndup

def strndup(str: str | None, n: int) -> str | None

Duplicates the first n bytes of a string, returning a newly-allocated buffer n + 1 bytes long which will always be nul-terminated. If str is less than n bytes long the buffer is padded with nuls. If str is NULL it returns NULL.

To copy a number of characters from a UTF-8 encoded string, use utf8_strncpy instead.

Parameters:

  • str — the string to duplicate
  • n — the maximum number of bytes to copy from str

strnfill

def strnfill(length: int, fill_char: int) -> str

Creates a new string length bytes long filled with fill_char.

Parameters:

  • length — the length of the new string
  • fill_char — the byte to fill the string with

strreverse

def strreverse(string: str) -> str

Reverses all of the bytes in a string. For example, g_strreverse ("abcdef") will result in "fedcba".

Note that g_strreverse() doesn't work on UTF-8 strings containing multibyte characters. For that purpose, use utf8_strreverse.

Parameters:

  • string — the string to reverse

strrstr

def strrstr(haystack: str, needle: str) -> str | None

Searches the string haystack for the last occurrence of the string needle.

The fact that this function returns gchar * rather than const gchar * is a historical artifact.

Parameters:

  • haystack — a string to search in
  • needle — the string to search for

strrstr_len

def strrstr_len(haystack: str, haystack_len: int, needle: str) -> str | None

Searches the string haystack for the last occurrence of the string needle, limiting the length of the search to haystack_len.

The fact that this function returns gchar * rather than const gchar * is a historical artifact.

Parameters:

  • haystack — a string to search in
  • haystack_len — the maximum length of haystack in bytes. A length of -1 can be used to mean "search the entire string", like strrstr
  • needle — the string to search for

strsignal

def strsignal(signum: int) -> str

Returns a string describing the given signal, e.g. "Segmentation fault". If the signal is unknown, it returns “unknown signal (<signum>)”.

You should use this function in preference to strsignal(), because it returns a string in UTF-8 encoding, and since not all platforms support the strsignal() function.

Parameters:

  • signum — the signal number. See the signal documentation

strsplit

def strsplit(string: str, delimiter: str, max_tokens: int) -> list[str]

Splits a string into a maximum of max_tokens pieces, using the given delimiter. If max_tokens is reached, the remainder of string is appended to the last token.

As an example, the result of g_strsplit (":a:bc::d:", ":", -1) is an array containing the six strings "", "a", "bc", "", "d" and "".

As a special case, the result of splitting the empty string "" is an empty array, not an array containing a single string. The reason for this special case is that being able to represent an empty array is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you'll need to check for the empty string before calling g_strsplit().

Parameters:

  • string — a string to split
  • delimiter — a string which specifies the places at which to split the string. The delimiter is not included in any of the resulting strings, unless max_tokens is reached.
  • max_tokens — the maximum number of pieces to split string into If this is less than 1, the string is split completely

strsplit_set

def strsplit_set(string: str, delimiters: list[int], max_tokens: int) -> list[str]

Splits string into a number of tokens not containing any of the bytes in delimiters.

A token is the (possibly empty) longest string that does not contain any of the bytes in delimiters. Note that separators will only be single bytes from delimiters. If max_tokens is reached, the remainder is appended to the last token.

For example, the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is an array containing the three strings "abc", "def", and "ghi".

The result of g_strsplit_set (":def/ghi:/x", ":/", -1) is an array containing the five strings "", "def", "ghi", "", "x".

As a special case, the result of splitting the empty string "" is an empty array, not an array containing a single string. The reason for this special case is that being able to represent an empty array is typically more useful than consistent handling of empty elements. If you do need to represent empty elements, you'll need to check for the empty string before calling g_strsplit_set().

Note that this function works on bytes not characters, so it can't be used to delimit UTF-8 strings for anything but ASCII characters.

Parameters:

  • string — a string to split
  • delimiters — a nul-terminated byte array containing bytes that are used to split the string; can be empty (just a nul byte), which will result in no string splitting
  • max_tokens — the maximum number of tokens to split string into. If this is less than 1, the string is split completely

strstr_len

def strstr_len(haystack: str, haystack_len: int, needle: str) -> str | None

Searches the string haystack for the first occurrence of the string needle, limiting the length of the search to haystack_len or a nul terminator byte (whichever is reached first).

A length of -1 can be used to mean “search the entire string”, like strstr().

The fact that this function returns gchar * rather than const gchar * is a historical artifact.

Parameters:

  • haystack — a string to search in
  • haystack_len — the maximum length of haystack in bytes, or -1 to search it entirely
  • needle — the string to search for

strtod

def strtod(nptr: str) -> tuple[float, str]

Converts a string to a floating point value.

It calls the standard strtod() function to handle the conversion, but if the string is not completely converted it attempts the conversion again with ascii_strtod, and returns the best match.

This function should seldom be used. The normal situation when reading numbers not for human consumption is to use ascii_strtod. Only when you know that you must expect both locale formatted and C formatted numbers should you use this. Make sure that you don't pass strings such as comma separated lists of values, since the commas may be interpreted as a decimal point in some locales, causing unexpected results.

Parameters:

  • nptr — the string to convert to a numeric value

strup

def strup(string: str) -> str

:::warning Deprecated since 2.2 This API is deprecated. :::

Converts a string to upper case.

Parameters:

  • string — the string to convert

strv_contains

def strv_contains(strv: list[str], str: str) -> bool

Checks if an array of strings contains the string str according to str_equal. strv must not be NULL.

Parameters:

  • strv — an array of strings to search in
  • str — the string to search for

strv_equal

def strv_equal(strv1: list[str], strv2: list[str]) -> bool

Checks if two arrays of strings contain exactly the same elements in exactly the same order.

Elements are compared using str_equal. To match independently of order, sort the arrays first (using qsort_with_data or similar).

Two empty arrays are considered equal. Neither strv1 nor strv2 may be NULL.

Parameters:

  • strv1 — an array of strings to compare to strv2
  • strv2 — an array of strings to compare to strv1

strv_get_type

def strv_get_type() -> type | GObject.Type

strv_length

def strv_length(str_array: list[str]) -> int

Returns the length of an array of strings. str_array must not be NULL.

Parameters:

  • str_array — an array of strings

test_add_data_func

def test_add_data_func(testpath: str, test_data: int | None, test_func: TestDataFunc) -> None

Creates a new test case.

This function is similar to GLib.test_create_case. However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the /-separated portions of testpath. The test_data argument will be passed as first argument to test_func.

If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or test_trap_subprocess.

No component of testpath may start with a dot (.) if the TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to do so even if it isn’t.

Parameters:

  • testpath — a /-separated name for the test
  • test_data — data for the test_func
  • test_func — the test function to invoke for this test

test_add_data_func_full

def test_add_data_func_full(testpath: str, test_data: int | None, test_func: TestDataFunc) -> None

Creates a new test case.

In contrast to test_add_data_func, this function is freeing test_data after the test run is complete.

Parameters:

  • testpath — a /-separated name for the test
  • test_data — data for test_func
  • test_func — the test function to invoke for this test

test_add_func

def test_add_func(testpath: str, test_func: TestFunc) -> None

Creates a new test case.

This function is similar to GLib.test_create_case. However the test is assumed to use no fixture, and test suites are automatically created on the fly and added to the root fixture, based on the /-separated portions of testpath.

If testpath includes the component "subprocess" anywhere in it, the test will be skipped by default, and only run if explicitly required via the -p command-line option or test_trap_subprocess.

No component of testpath may start with a dot (.) if the TEST_OPTION_ISOLATE_DIRS option is being used; and it is recommended to do so even if it isn’t.

Parameters:

  • testpath — a /-separated name for the test
  • test_func — the test function to invoke for this test

test_assert_expected_messages_internal

def test_assert_expected_messages_internal(domain: str, file: str, line: int, func: str) -> None

test_bug

def test_bug(bug_uri_snippet: str) -> None

Adds a message to test reports that associates a bug URI with a test case.

Bug URIs are constructed from a base URI set with test_bug_base and bug_uri_snippet. If test_bug_base has not been called, it is assumed to be the empty string, so a full URI can be provided to test_bug instead.

See also test_summary.

Since GLib 2.70, the base URI is not prepended to bug_uri_snippet if it is already a valid URI.

Parameters:

  • bug_uri_snippet — Bug specific bug tracker URI or URI portion.

test_bug_base

def test_bug_base(uri_pattern: str) -> None

Specifies the base URI for bug reports.

The base URI is used to construct bug report messages for GLib.test_message when test_bug is called. Calling this function outside of a test case sets the default base URI for all test cases. Calling it from within a test case changes the base URI for the scope of the test case only. Bug URIs are constructed by appending a bug specific URI portion to uri_pattern, or by replacing the special string %s within uri_pattern if that is present.

If test_bug_base is not called, bug URIs are formed solely from the value provided by test_bug.

Parameters:

  • uri_pattern — the base pattern for bug URIs

test_disable_crash_reporting

def test_disable_crash_reporting() -> None

Attempts to disable system crash reporting infrastructure.

This function should be called before exercising code paths that are expected or intended to crash, to avoid wasting resources in system-wide crash collection infrastructure such as systemd-coredump or abrt.

test_expect_message

def test_expect_message(log_domain: str | None, log_level: LogLevelFlags | int, pattern: str) -> None

Indicates that a message with the given log_domain and log_level, with text matching pattern, is expected to be logged.

When this message is logged, it will not be printed, and the test case will not abort.

This API may only be used with the old logging API (GLib.log without G_LOG_USE_STRUCTURED defined). It will not work with the structured logging API. See Testing for Messages.

Use GLib.test_assert_expected_messages to assert that all previously-expected messages have been seen and suppressed.

You can call this multiple times in a row, if multiple messages are expected as a result of a single call. (The messages must appear in the same order as the calls to test_expect_message.)

For example:

// g_main_context_push_thread_default() should fail if the
// context is already owned by another thread.
g_test_expect_message (G_LOG_DOMAIN,
                       G_LOG_LEVEL_CRITICAL,
                       "assertion*acquired_context*failed");
g_main_context_push_thread_default (bad_context);
g_test_assert_expected_messages ();

Note that you cannot use this to test GLib.error messages, since GLib.error intentionally never returns even if the program doesn’t abort; use test_trap_subprocess in this case.

If messages at LogLevelFlags.LEVEL_DEBUG are emitted, but not explicitly expected via test_expect_message then they will be ignored.

Parameters:

  • log_domain — the log domain of the message
  • log_level — the log level of the message
  • pattern — a glob-style pattern (see PatternSpec)

test_fail

def test_fail() -> None

Indicates that a test failed.

This function can be called multiple times from the same test. You can use this function if your test failed in a recoverable way.

Do not use this function if the failure of a test could cause other tests to malfunction.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

Note that unlike test_skip and test_incomplete, this function does not log a message alongside the test failure. If details of the test failure are available, either log them with GLib.test_message before test_fail, or use GLib.test_fail_printf instead.

test_failed

def test_failed() -> bool

Returns whether a test has already failed.

This will be the case when test_fail, test_incomplete or test_skip have been called, but also if an assertion has failed.

This can be useful to return early from a test if continuing after a failed assertion might be harmful.

The return value of this function is only meaningful if it is called from inside a test function.

test_get_dir

def test_get_dir(file_type: TestFileType | int) -> str

Gets the pathname of the directory containing test files of the type specified by file_type.

This is approximately the same as calling g_test_build_filename("."), but you don't need to free the return value.

Parameters:

  • file_type — the type of file (built vs. distributed)

test_get_path

def test_get_path() -> str

Gets the test path for the test currently being run.

In essence, it will be the same string passed as the first argument to e.g. GLib.test_add when the test was added.

This function returns a valid string only within a test function.

Note that this is a test path, not a file system path.

test_incomplete

def test_incomplete(msg: str | None = ...) -> None

Indicates that a test failed because of some incomplete functionality.

This function can be called multiple times from the same test.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

Parameters:

  • msg — explanation

test_log_type_name

def test_log_type_name(log_type: TestLogType | int) -> str

test_queue_destroy

def test_queue_destroy(destroy_func: DestroyNotify, destroy_data: int | None = ...) -> None

Enqueues a callback destroy_func to be executed during the next test case teardown phase.

This is most useful to auto destroy allocated test resources at the end of a test run. Resources are released in reverse queue order, that means enqueueing callback A before callback B will cause B() to be called before A() during teardown.

Parameters:

  • destroy_func — destroy callback for teardown phase
  • destroy_data — destroy callback data

test_queue_free

def test_queue_free(gfree_pointer: int | None = ...) -> None

Enqueues a pointer to be released with free during the next teardown phase.

This is equivalent to calling test_queue_destroy with a destroy callback of free.

Parameters:

  • gfree_pointer — the pointer to be stored

test_rand_double

def test_rand_double() -> float

Gets a reproducible random floating point number.

See test_rand_int for details on test case random numbers.

test_rand_double_range

def test_rand_double_range(range_start: float, range_end: float) -> float

Gets a reproducible random floating point number out of a specified range.

See test_rand_int for details on test case random numbers.

Parameters:

  • range_start — the minimum value returned by this function
  • range_end — the minimum value not returned by this function

test_rand_int

def test_rand_int() -> int

Gets a reproducible random integer number.

The random numbers generated by the g_test_rand_*() family of functions change with every new test program start, unless the --seed option is given when starting test programs.

For individual test cases however, the random number generator is reseeded, to avoid dependencies between tests and to make --seed effective for all test cases.

test_rand_int_range

def test_rand_int_range(begin: int, end: int) -> int

Gets a reproducible random integer number out of a specified range.

See test_rand_int for details on test case random numbers.

Parameters:

  • begin — the minimum value returned by this function
  • end — the smallest value not to be returned by this function

test_run

def test_run() -> int

Runs all tests under the toplevel suite.

The toplevel suite can be retrieved with GLib.test_get_root.

Similar to test_run_suite, the test cases to be run are filtered according to test path arguments (-p testpath and -s testpath) as parsed by GLib.test_init. test_run_suite or test_run may only be called once in a program.

In general, the tests and sub-suites within each suite are run in the order in which they are defined. However, note that prior to GLib 2.36, there was a bug in the g_test_add_* functions which caused them to create multiple suites with the same name, meaning that if you created tests "/foo/simple", "/bar/simple", and "/foo/using-bar" in that order, they would get run in that order (since test_run would run the first "/foo" suite, then the "/bar" suite, then the second "/foo" suite). As of 2.36, this bug is fixed, and adding the tests in that order would result in a running order of "/foo/simple", "/foo/using-bar", "/bar/simple". If this new ordering is sub-optimal (because it puts more-complicated tests before simpler ones, making it harder to figure out exactly what has failed), you can fix it by changing the test paths to group tests by suite in a way that will result in the desired running order. Eg, "/simple/foo", "/simple/bar", "/complex/foo-using-bar".

However, you should never make the actual result of a test depend on the order that tests are run in. If you need to ensure that some particular code runs before or after a given test case, use GLib.test_add, which lets you specify setup and teardown functions.

If all tests are skipped or marked as incomplete (expected failures), this function will return 0 if producing TAP output, or 77 (treated as "skip test" by Automake) otherwise.

test_run_suite

def test_run_suite(suite: TestSuite) -> int

Executes the tests within suite and all nested test suites.

The test suites to be executed are filtered according to test path arguments (-p testpath and -s testpath) as parsed by GLib.test_init. See the test_run documentation for more information on the order that tests are run in.

test_run_suite or test_run may only be called once in a program.

Parameters:

  • suite — a test suite

test_set_nonfatal_assertions

def test_set_nonfatal_assertions() -> None

Changes the behaviour of the various assertion macros.

The g_assert_*() macros, g_test_assert_expected_messages() and the various g_test_trap_assert_*() macros are changed to not abort to program.

Instead, they will call test_fail and continue. (This also changes the behavior of test_fail so that it will not cause the test program to abort after completing the failed test.)

Note that the GLib.assert_not_reached and GLib.assert macros are not affected by this.

This function can only be called after GLib.test_init.

test_skip

def test_skip(msg: str | None = ...) -> None

Indicates that a test was skipped.

Calling this function will not stop the test from running, you need to return from the test function yourself. So you can produce additional diagnostic messages or even continue running the test.

If not called from inside a test, this function does nothing.

Parameters:

  • msg — explanation

test_subprocess

def test_subprocess() -> bool

Returns true if the test program is running under test_trap_subprocess.

test_summary

def test_summary(summary: str) -> None

Sets the summary for a test.

This may be included in test report output, and is useful documentation for anyone reading the source code or modifying a test in future. It must be a single line, and it should summarise what the test checks, and how.

This should be called at the top of a test function.

For example:

static void
test_array_sort (void)
{
  g_test_summary ("Test my_array_sort() sorts the array correctly and stably, "
                  "including testing zero length and one-element arrays.");

  // ...
}

See also test_bug.

Parameters:

  • summary — summary of the test purpose

test_timer_elapsed

def test_timer_elapsed() -> float

Gets the number of seconds since the last start of the timer with test_timer_start.

test_timer_last

def test_timer_last() -> float

Reports the last result of test_timer_elapsed.

test_timer_start

def test_timer_start() -> None

Starts a timing test.

Call test_timer_elapsed when the task is supposed to be done. Call this function again to restart the timer.

test_trap_assertions

def test_trap_assertions(domain: str, file: str, line: int, func: str, assertion_flags: int, pattern: str) -> None

test_trap_fork

def test_trap_fork(usec_timeout: int, test_trap_flags: TestTrapFlags | int) -> bool

:::warning Deprecated This API is deprecated. :::

Forks the current test program to execute a test case that might not return or that might abort.

If usec_timeout is non-0, the forked test case is aborted and considered failing if its run time exceeds it.

The forking behavior can be configured with TestTrapFlags flags.

In the following example, the test code forks, the forked child process produces some sample output and exits successfully. The forking parent process then asserts successful child program termination and validates child program outputs.

  static void
  test_fork_patterns (void)
  {
    if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
      {
        g_print ("some stdout text: somagic17
");
        g_printerr ("some stderr text: semagic43
");
        exit (0); // successful test run
      }
    g_test_trap_assert_passed ();
    g_test_trap_assert_stdout ("*somagic17*");
    g_test_trap_assert_stderr ("*semagic43*");
  }

Parameters:

  • usec_timeout — timeout for the forked test in microseconds
  • test_trap_flags — flags to modify forking behaviour

test_trap_has_passed

def test_trap_has_passed() -> bool

Checks the result of the last test_trap_subprocess call.

test_trap_has_skipped

def test_trap_has_skipped() -> bool

Checks the result of the last test_trap_subprocess call.

test_trap_reached_timeout

def test_trap_reached_timeout() -> bool

Checks the result of the last test_trap_subprocess call.

test_trap_subprocess

def test_trap_subprocess(test_path: str | None, usec_timeout: int, test_flags: TestSubprocessFlags | int) -> None

Respawns the test program to run only test_path in a subprocess.

This is equivalent to calling test_trap_subprocess_with_envp with envp set to NULL. See the documentation for that function for full details.

Parameters:

  • test_path — test to run in a subprocess
  • usec_timeout — timeout for the subprocess test in microseconds.
  • test_flags — flags to modify subprocess behaviour

test_trap_subprocess_with_envp

def test_trap_subprocess_with_envp(test_path: str | None, envp: list[str | bytes | os.PathLike[str] | os.PathLike[bytes]] | None, usec_timeout: int, test_flags: TestSubprocessFlags | int) -> None

Respawns the test program to run only test_path in a subprocess with a given environment.

This can be used for a test case that might not return, or that might abort.

If test_path is NULL then the same test is re-run in a subprocess. You can use test_subprocess to determine whether the test is in a subprocess or not.

test_path can also be the name of the parent test, followed by "/subprocess/" and then a name for the specific subtest (or just ending with "/subprocess" if the test only has one child test); tests with names of this form will automatically be skipped in the parent process.

If envp is NULL, the parent process’ environment will be inherited.

If usec_timeout is non-0, the test subprocess is aborted and considered failing if its run time exceeds it.

The subprocess behavior can be configured with TestSubprocessFlags flags.

You can use methods such as GLib.test_trap_assert_passed, GLib.test_trap_assert_failed, and GLib.test_trap_assert_stderr to check the results of the subprocess. (But note that GLib.test_trap_assert_stdout and GLib.test_trap_assert_stderr cannot be used if test_flags specifies that the child should inherit the parent stdout/stderr.)

If your main () needs to behave differently in the subprocess, you can call test_subprocess (after calling GLib.test_init) to see whether you are in a subprocess.

Internally, this function tracks the child process using child_watch_source_new, so your process must not ignore SIGCHLD, and must not attempt to watch or wait for the child process via another mechanism.

The following example tests that calling my_object_new(1000000) will abort with an error message.

  static void
  test_create_large_object (void)
  {
    if (g_test_subprocess ())
      {
        my_object_new (1000000);
        return;
      }

    // Reruns this same test in a subprocess
    g_test_trap_subprocess (NULL, 0, G_TEST_SUBPROCESS_DEFAULT);
    g_test_trap_assert_failed ();
    g_test_trap_assert_stderr ("*ERROR*too large*");
  }

  static void
  test_different_username (void)
  {
    if (g_test_subprocess ())
      {
        // Code under test goes here
        g_message ("Username is now simulated as %s", g_getenv ("USER"));
        return;
      }

    // Reruns this same test in a subprocess
    g_auto(GStrv) envp = g_get_environ ();
    envp = g_environ_setenv (g_steal_pointer (&envp), "USER", "charlie", TRUE);
    g_test_trap_subprocess_with_envp (NULL, envp, 0, G_TEST_SUBPROCESS_DEFAULT);
    g_test_trap_assert_passed ();
    g_test_trap_assert_stdout ("Username is now simulated as charlie");
  }

  int
  main (int argc, char **argv)
  {
    g_test_init (&argc, &argv, NULL);

    g_test_add_func ("/myobject/create-large-object",
                     test_create_large_object);
    g_test_add_func ("/myobject/different-username",
                     test_different_username);
    return g_test_run ();
  }

Parameters:

  • test_path — test to run in a subprocess
  • envp — environment to run the test in
  • usec_timeout — timeout for the subprocess test in microseconds
  • test_flags — flags to modify subprocess behaviour

timeout_add

def timeout_add(priority: int, interval: int, function: SourceFunc) -> int

Sets a function to be called at regular intervals, with the given priority.

The function is called repeatedly until it returns SOURCE_REMOVE, at which point the timeout is automatically destroyed and the function will not be called again. The notify function is called when the timeout is destroyed. The first call to the function will be at the end of the first interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval (it does not try to ‘catch up’ time lost in delays).

See main loop memory management for details on how to handle the return value and memory management of data.

This internally creates a main loop source using timeout_source_new and attaches it to the global MainContext using Source.attach, so the callback will be invoked in whichever thread is running that main context. You can do these steps manually if you need greater control or to use a custom main context.

The interval given is in terms of monotonic time, not wall clock time. See get_monotonic_time.

Parameters:

  • priority — the priority of the timeout source; typically this will be in the range between PRIORITY_DEFAULT and PRIORITY_HIGH
  • interval — the time between calls to the function, in milliseconds
  • function — function to call

timeout_add_seconds

def timeout_add_seconds(priority: int, interval: int, function: SourceFunc) -> int

Sets a function to be called at regular intervals, with priority.

The function is called repeatedly until it returns SOURCE_REMOVE, at which point the timeout is automatically destroyed and the function will not be called again.

Unlike timeout_add, this function operates at whole second granularity. The initial starting point of the timer is determined by the implementation and the implementation is expected to group multiple timers together so that they fire all at the same time. To allow this grouping, the interval to the first timer is rounded and can deviate up to one second from the specified interval. Subsequent timer iterations will generally run at the specified interval.

Note that timeout functions may be delayed, due to the processing of other event sources. Thus they should not be relied on for precise timing. After each call to the timeout function, the time of the next timeout is recalculated based on the current time and the given interval

See main loop memory management for details on how to handle the return value and memory management of data.

If you want timing more precise than whole seconds, use timeout_add instead.

The grouping of timers to fire at the same time results in a more power and CPU efficient behavior so if your timer is in multiples of seconds and you don’t require the first timer exactly one second from now, the use of timeout_add_seconds is preferred over timeout_add.

This internally creates a main loop source using timeout_source_new_seconds and attaches it to the main loop context using Source.attach. You can do these steps manually if you need greater control.

It is safe to call this function from any thread.

The interval given is in terms of monotonic time, not wall clock time. See get_monotonic_time.

Parameters:

  • priority — the priority of the timeout source; typically this will be in the range between PRIORITY_DEFAULT and PRIORITY_HIGH
  • interval — the time between calls to the function, in seconds
  • function — function to call

timeout_source_new

def timeout_source_new(interval: int) -> Source

Creates a new timeout source.

The source will not initially be associated with any MainContext and must be added to one with Source.attach before it will be executed.

The interval given is in terms of monotonic time, not wall clock time. See get_monotonic_time.

Parameters:

  • interval — the timeout interval in milliseconds

timeout_source_new_seconds

def timeout_source_new_seconds(interval: int) -> Source

Creates a new timeout source.

The source will not initially be associated with any MainContext and must be added to one with Source.attach before it will be executed.

The scheduling granularity/accuracy of this timeout source will be in seconds.

The interval given is in terms of monotonic time, not wall clock time. See get_monotonic_time.

Parameters:

  • interval — the timeout interval in seconds

try_malloc

def try_malloc(n_bytes: int) -> int | None

Attempts to allocate n_bytes, and returns None on failure. Contrast with malloc, which aborts the program on failure.

Parameters:

  • n_bytes — number of bytes to allocate.

try_malloc0

def try_malloc0(n_bytes: int) -> int | None

Attempts to allocate n_bytes, initialized to 0's, and returns None on failure. Contrast with malloc0, which aborts the program on failure.

Parameters:

  • n_bytes — number of bytes to allocate

try_malloc0_n

def try_malloc0_n(n_blocks: int, n_block_bytes: int) -> int | None

This function is similar to try_malloc0, allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

Parameters:

  • n_blocks — the number of blocks to allocate
  • n_block_bytes — the size of each block in bytes

try_malloc_n

def try_malloc_n(n_blocks: int, n_block_bytes: int) -> int | None

This function is similar to try_malloc, allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

Parameters:

  • n_blocks — the number of blocks to allocate
  • n_block_bytes — the size of each block in bytes

try_realloc

def try_realloc(mem: int | None, n_bytes: int) -> int | None

Attempts to realloc mem to a new size, n_bytes, and returns None on failure. Contrast with realloc, which aborts the program on failure.

If mem is None, behaves the same as try_malloc.

Parameters:

  • mem — previously-allocated memory, or None.
  • n_bytes — number of bytes to allocate.

try_realloc_n

def try_realloc_n(mem: int | None, n_blocks: int, n_block_bytes: int) -> int | None

This function is similar to try_realloc, allocating (n_blocks * n_block_bytes) bytes, but care is taken to detect possible overflow during multiplication.

Parameters:

  • mem — previously-allocated memory, or None.
  • n_blocks — the number of blocks to allocate
  • n_block_bytes — the size of each block in bytes

ucs4_to_utf16

def ucs4_to_utf16(str: list[str]) -> tuple[int, int, int]

Convert a string from UCS-4 to UTF-16.

A nul character (U+0000) will be added to the result after the converted text.

Parameters:

  • str — a UCS-4 encoded string

ucs4_to_utf8

def ucs4_to_utf8(str: list[str]) -> tuple[str, int, int]

Convert a string from a 32-bit fixed width representation as UCS-4. to UTF-8.

The result will be terminated with a nul byte.

Parameters:

  • str — a UCS-4 encoded string

unichar_break_type

def unichar_break_type(c: str) -> UnicodeBreakType

Determines the break type of c. c should be a Unicode character (to derive a character from UTF-8 encoded text, use utf8_get_char). The break type is used to find word and line breaks ("text boundaries"), Pango implements the Unicode boundary resolution algorithms and normally you would use a function such as Pango.break_ instead of caring about break types yourself.

Parameters:

  • c — a Unicode character

unichar_combining_class

def unichar_combining_class(uc: str) -> int

Determines the canonical combining class of a Unicode character.

Parameters:

  • uc — a Unicode character

unichar_compose

def unichar_compose(a: str, b: str) -> tuple[bool, str]

Performs a single composition step of the Unicode canonical composition algorithm.

This function includes algorithmic Hangul Jamo composition, but it is not exactly the inverse of unichar_decompose. No composition can have either of a or b equal to zero. To be precise, this function composes if and only if there exists a Primary Composite P which is canonically equivalent to the sequence <a,b>. See the Unicode Standard for the definition of Primary Composite.

If a and b do not compose a new character, ch is set to zero.

See UAX#15 for details.

Parameters:

  • a — a Unicode character
  • b — a Unicode character

unichar_decompose

def unichar_decompose(ch: str) -> tuple[bool, str, str]

Performs a single decomposition step of the Unicode canonical decomposition algorithm.

This function does not include compatibility decompositions. It does, however, include algorithmic Hangul Jamo decomposition, as well as 'singleton' decompositions which replace a character by a single other character. In the case of singletons *b will be set to zero.

If ch is not decomposable, *a is set to ch and *b is set to zero.

Note that the way Unicode decomposition pairs are defined, it is guaranteed that b would not decompose further, but a may itself decompose. To get the full canonical decomposition for ch, one would need to recursively call this function on a. Or use unichar_fully_decompose.

See UAX#15 for details.

Parameters:

  • ch — a Unicode character

unichar_digit_value

def unichar_digit_value(c: str) -> int

Determines the numeric value of a character as a decimal digit.

Parameters:

  • c — a Unicode character

unichar_fully_decompose

def unichar_fully_decompose(ch: str, compat: bool, result_len: int) -> tuple[int, str]

Computes the canonical or compatibility decomposition of a Unicode character. For compatibility decomposition, pass True for compat; for canonical decomposition pass False for compat.

The decomposed sequence is placed in result. Only up to result_len characters are written into result. The length of the full decomposition (irrespective of result_len) is returned by the function. For canonical decomposition, currently all decompositions are of length at most 4, but this may change in the future (very unlikely though). At any rate, Unicode does guarantee that a buffer of length 18 is always enough for both compatibility and canonical decompositions, so that is the size recommended. This is provided as UNICHAR_MAX_DECOMPOSITION_LENGTH.

See UAX#15 for details.

Parameters:

  • ch — a Unicode character.
  • compat — whether perform canonical or compatibility decomposition
  • result_len — length of result

unichar_get_mirror_char

def unichar_get_mirror_char(ch: str) -> tuple[bool, str]

In Unicode, some characters are "mirrored". This means that their images are mirrored horizontally in text that is laid out from right to left. For instance, "(" would become its mirror image, ")", in right-to-left text.

If ch has the Unicode mirrored property and there is another unicode character that typically has a glyph that is the mirror image of ch's glyph and mirrored_ch is set, it puts that character in the address pointed to by mirrored_ch. Otherwise the original character is put.

Parameters:

  • ch — a Unicode character

unichar_get_script

def unichar_get_script(ch: str) -> UnicodeScript

Looks up the UnicodeScript for a particular character (as defined by Unicode Standard Annex #24). No check is made for ch being a valid Unicode character; if you pass in invalid character, the result is undefined.

This function is equivalent to Pango.Script.for_unichar and the two are interchangeable.

Parameters:

  • ch — a Unicode character

unichar_isalnum

def unichar_isalnum(c: str) -> bool

Determines whether a character is alphanumeric. Given some UTF-8 text, obtain a character value with utf8_get_char.

Parameters:

  • c — a Unicode character

unichar_isalpha

def unichar_isalpha(c: str) -> bool

Determines whether a character is alphabetic (i.e. a letter). Given some UTF-8 text, obtain a character value with utf8_get_char.

Parameters:

  • c — a Unicode character

unichar_iscntrl

def unichar_iscntrl(c: str) -> bool

Determines whether a character is a control character. Given some UTF-8 text, obtain a character value with utf8_get_char.

Parameters:

  • c — a Unicode character

unichar_isdefined

def unichar_isdefined(c: str) -> bool

Determines if a given character is assigned in the Unicode standard.

Parameters:

  • c — a Unicode character

unichar_isdigit

def unichar_isdigit(c: str) -> bool

Determines whether a character is numeric (i.e. a digit). This covers ASCII 0-9 and also digits in other languages/scripts. Given some UTF-8 text, obtain a character value with utf8_get_char.

Parameters:

  • c — a Unicode character

unichar_isgraph

def unichar_isgraph(c: str) -> bool

Determines whether a character is printable and not a space (returns False for control characters, format characters, and spaces). unichar_isprint is similar, but returns True for spaces. Given some UTF-8 text, obtain a character value with utf8_get_char.

Parameters:

  • c — a Unicode character

unichar_islower

def unichar_islower(c: str) -> bool

Determines whether a character is a lowercase letter. Given some UTF-8 text, obtain a character value with utf8_get_char.

Parameters:

  • c — a Unicode character

unichar_ismark

def unichar_ismark(c: str) -> bool

Determines whether a character is a mark (non-spacing mark, combining mark, or enclosing mark in Unicode speak). Given some UTF-8 text, obtain a character value with utf8_get_char.

Note: in most cases where isalpha characters are allowed, ismark characters should be allowed to as they are essential for writing most European languages as well as many non-Latin scripts.

Parameters:

  • c — a Unicode character

unichar_isprint

def unichar_isprint(c: str) -> bool

Determines whether a character is printable. Unlike unichar_isgraph, returns True for spaces. Given some UTF-8 text, obtain a character value with utf8_get_char.

Parameters:

  • c — a Unicode character

unichar_ispunct

def unichar_ispunct(c: str) -> bool

Determines whether a character is punctuation or a symbol. Given some UTF-8 text, obtain a character value with utf8_get_char.

Parameters:

  • c — a Unicode character

unichar_isspace

def unichar_isspace(c: str) -> bool

Determines whether a character is a space, tab, or line separator (newline, carriage return, etc.). Given some UTF-8 text, obtain a character value with utf8_get_char.

(Note: don't use this to do word breaking; you have to use Pango or equivalent to get word breaking right, the algorithm is fairly complex.)

Parameters:

  • c — a Unicode character

unichar_istitle

def unichar_istitle(c: str) -> bool

Determines if a character is titlecase. Some characters in Unicode which are composites, such as the DZ digraph have three case variants instead of just two. The titlecase form is used at the beginning of a word where only the first letter is capitalized. The titlecase form of the DZ digraph is U+01F2 LATIN CAPITAL LETTTER D WITH SMALL LETTER Z.

Parameters:

  • c — a Unicode character

unichar_isupper

def unichar_isupper(c: str) -> bool

Determines if a character is uppercase.

Parameters:

  • c — a Unicode character

unichar_iswide

def unichar_iswide(c: str) -> bool

Determines if a character is typically rendered in a double-width cell.

Parameters:

  • c — a Unicode character

unichar_iswide_cjk

def unichar_iswide_cjk(c: str) -> bool

Determines if a character is typically rendered in a double-width cell under legacy East Asian locales. If a character is wide according to unichar_iswide, then it is also reported wide with this function, but the converse is not necessarily true. See the Unicode Standard Annex #11 for details.

If a character passes the unichar_iswide test then it will also pass this test, but not the other way around. Note that some characters may pass both this test and unichar_iszerowidth.

Parameters:

  • c — a Unicode character

unichar_isxdigit

def unichar_isxdigit(c: str) -> bool

Determines if a character is a hexadecimal digit.

Parameters:

  • c — a Unicode character.

unichar_iszerowidth

def unichar_iszerowidth(c: str) -> bool

Determines if a given character typically takes zero width when rendered. The return value is True for all non-spacing and enclosing marks (e.g., combining accents), format characters, zero-width space, but not U+00AD SOFT HYPHEN.

A typical use of this function is with one of unichar_iswide or unichar_iswide_cjk to determine the number of cells a string occupies when displayed on a grid display (terminals). However, note that not all terminals support zero-width rendering of zero-width marks.

Parameters:

  • c — a Unicode character

unichar_to_utf8

def unichar_to_utf8(c: str) -> tuple[int, str]

Converts a single character to UTF-8.

Parameters:

  • c — a Unicode character code

unichar_tolower

def unichar_tolower(c: str) -> str

Converts a character to lower case.

Parameters:

  • c — a Unicode character.

unichar_totitle

def unichar_totitle(c: str) -> str

Converts a character to the titlecase.

Parameters:

  • c — a Unicode character

unichar_toupper

def unichar_toupper(c: str) -> str

Converts a character to uppercase.

Parameters:

  • c — a Unicode character

unichar_type

def unichar_type(c: str) -> UnicodeType

Classifies a Unicode character by type.

Parameters:

  • c — a Unicode character

unichar_validate

def unichar_validate(ch: str) -> bool

Checks whether ch is a valid Unicode character.

Some possible integer values of ch will not be valid. U+0000 is considered a valid character, though it’s normally a string terminator.

Parameters:

  • ch — a Unicode character

unichar_xdigit_value

def unichar_xdigit_value(c: str) -> int

Determines the numeric value of a character as a hexadecimal digit.

Parameters:

  • c — a Unicode character

unicode_canonical_decomposition

def unicode_canonical_decomposition(ch: str, result_len: int) -> str

:::warning Deprecated since 2.30 This API is deprecated. :::

Computes the canonical decomposition of a Unicode character.

Parameters:

  • ch — a Unicode character.
  • result_len — location to store the length of the return value.

unicode_canonical_ordering

def unicode_canonical_ordering(string: list[str]) -> None

Computes the canonical ordering of a string in-place. This rearranges decomposed characters in the string according to their combining classes. See the Unicode manual for more information.

Parameters:

  • string — a UCS-4 encoded string.

unix_closefrom

def unix_closefrom(lowfd: int) -> int

Close every file descriptor equal to or greater than lowfd.

Typically lowfd will be 3, to leave standard input, standard output and standard error open.

This is the same as Linux close_range (lowfd, ~0U, 0), but portable to other OSs and to older versions of Linux. Equivalently, it is the same as BSD closefrom (lowfd), but portable, and async-signal-safe on all OSs.

This function is async-signal safe, making it safe to call from a signal handler or a SpawnChildSetupFunc, as long as lowfd is non-negative. See signal(7) and signal-safety(7) for more details.

Parameters:

  • lowfd — Minimum fd to close, which must be non-negative

unix_error_quark

def unix_error_quark() -> Quark

unix_fd_add_full

def unix_fd_add_full(priority: int, fd: int, condition: IOCondition | int, function: FDSourceFunc) -> int

Sets a function to be called when the IO condition, as specified by condition becomes true for fd.

This is the same as g_unix_fd_add(), except that it allows you to specify a non-default priority and a provide a GDestroyNotify for user_data.

Parameters:

  • priority — the priority of the source
  • fd — a file descriptor
  • condition — IO conditions to watch for on fd
  • function — a GUnixFDSourceFunc

unix_fd_query_path

def unix_fd_query_path(fd: int) -> str

Queries the file path for the given FD opened by the current process.

Parameters:

  • fd — The file descriptor to query.

unix_fd_source_new

def unix_fd_source_new(fd: int, condition: IOCondition | int) -> Source

Creates a Source to watch for a particular I/O condition on a file descriptor.

The source will never close the fd — you must do it yourself.

Any callback attached to the returned Source must have type GUnixFDSourceFunc.

Parameters:

  • fd — a file descriptor
  • condition — I/O conditions to watch for on fd

unix_fdwalk_set_cloexec

def unix_fdwalk_set_cloexec(lowfd: int) -> int

Mark every file descriptor equal to or greater than lowfd to be closed at the next execve() or similar, as if via the FD_CLOEXEC flag.

Typically lowfd will be 3, to leave standard input, standard output and standard error open after exec.

This is the same as Linux close_range (lowfd, ~0U, CLOSE_RANGE_CLOEXEC), but portable to other OSs and to older versions of Linux.

This function is async-signal safe, making it safe to call from a signal handler or a SpawnChildSetupFunc, as long as lowfd is non-negative. See signal(7) and signal-safety(7) for more details.

Parameters:

  • lowfd — Minimum fd to act on, which must be non-negative

unix_get_passwd_entry

def unix_get_passwd_entry(user_name: str) -> int | None

Get the passwd file entry for the given user_name using getpwnam_r(). This can fail if the given user_name doesn’t exist.

The returned struct passwd has been allocated using malloc and should be freed using free. The strings referenced by the returned struct are included in the same allocation, so are valid until the struct passwd is freed.

This function is safe to call from multiple threads concurrently.

You will need to include pwd.h to get the definition of struct passwd.

Parameters:

  • user_name — the username to get the passwd file entry for

unix_open_pipe

def unix_open_pipe(fds: list[int], flags: int) -> bool

Similar to the UNIX pipe() call, but on modern systems like Linux uses the pipe2() system call, which atomically creates a pipe with the configured flags.

As of GLib 2.78, the supported flags are O_CLOEXEC/FD_CLOEXEC (see below) and O_NONBLOCK. Prior to GLib 2.78, only FD_CLOEXEC was supported — if you wanted to configure O_NONBLOCK then that had to be done separately with fcntl().

Since GLib 2.80, the constants G_UNIX_PIPE_END_READ and G_UNIX_PIPE_END_WRITE can be used as mnemonic indexes in fds.

It is a programmer error to call this function with unsupported flags, and a critical warning will be raised.

As of GLib 2.78, it is preferred to pass O_CLOEXEC in, rather than FD_CLOEXEC, as that matches the underlying pipe() API more closely. Prior to 2.78, only FD_CLOEXEC was supported. Support for FD_CLOEXEC may be deprecated and removed in future.

Parameters:

  • fds — Array of two integers
  • flags — Bitfield of file descriptor flags, as for fcntl()

unix_set_fd_nonblocking

def unix_set_fd_nonblocking(fd: int, nonblock: bool) -> bool

Control the non-blocking state of the given file descriptor, according to nonblock. On most systems this uses O_NONBLOCK, but on some older ones may use O_NDELAY.

Parameters:

  • fd — A file descriptor
  • nonblock — If True, set the descriptor to be non-blocking

unix_signal_add

def unix_signal_add(priority: int, signum: int, handler: SourceFunc) -> int

A convenience function for g_unix_signal_source_new(), which attaches to the default MainContext. You can remove the watch using Source.remove.

Parameters:

  • priority — the priority of the signal source. Typically this will be in the range between PRIORITY_DEFAULT and PRIORITY_HIGH.
  • signum — Signal number
  • handler — Callback

unix_signal_source_new

def unix_signal_source_new(signum: int) -> Source

Create a Source that will be dispatched upon delivery of the UNIX signal signum. In GLib versions before 2.36, only SIGHUP, SIGINT, SIGTERM can be monitored. In GLib 2.36, SIGUSR1 and SIGUSR2 were added. In GLib 2.54, SIGWINCH was added.

Note that unlike the UNIX default, all sources which have created a watch will be dispatched, regardless of which underlying thread invoked g_unix_signal_source_new().

For example, an effective use of this function is to handle SIGTERM cleanly; flushing any outstanding files, and then calling MainLoop.quit. It is not safe to do any of this from a regular UNIX signal handler; such a handler may be invoked while malloc() or another library function is running, causing reentrancy issues if the handler attempts to use those functions. None of the GLib/GObject API is safe against this kind of reentrancy.

The interaction of this source when combined with native UNIX functions like sigprocmask() is not defined.

The source will not initially be associated with any MainContext and must be added to one with Source.attach before it will be executed.

Parameters:

  • signum — A signal number
def unlink(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> int

A wrapper for the POSIX unlink() function. The unlink() function deletes a name from the filesystem. If this was the last link to the file and no processes have it opened, the diskspace occupied by the file is freed.

See your C library manual for more details about unlink(). Note that on Windows, it is in general not possible to delete files that are open to some process, or mapped into memory.

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)

unsetenv

def unsetenv(variable: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> None

Removes an environment variable from the environment.

Note that on some systems, when variables are overwritten, the memory used for the previous variables and its value isn't reclaimed.

You should be mindful of the fact that environment variable handling in UNIX is not thread-safe, and your program may crash if one thread calls unsetenv while another thread is calling getenv(). (And note that many functions, such as gettext(), call getenv() internally.) This function is only safe to use at the very start of your program, before creating any other threads (or creating objects that create worker threads of their own).

If you need to set up the environment for a child process, you can use get_environ to get an environment array, modify that with environ_setenv and environ_unsetenv, and then pass that array directly to execvpe(), spawn_async, or the like.

Parameters:

  • variable — the environment variable to remove, must not contain '='

usleep

def usleep(microseconds: int) -> None

Pauses the current thread for the given number of microseconds.

There are 1 million microseconds per second (represented by the USEC_PER_SEC macro). usleep may have limited precision, depending on hardware and operating system; don't rely on the exact length of the sleep.

Parameters:

  • microseconds — number of microseconds to pause

utf16_to_ucs4

def utf16_to_ucs4(str: list[int]) -> tuple[str, int, int]

Convert a string from UTF-16 to UCS-4.

The result will be nul-terminated.

Parameters:

  • str — a UTF-16 encoded string

utf16_to_utf8

def utf16_to_utf8(str: list[int]) -> tuple[str, int, int]

Convert a string from UTF-16 to UTF-8.

The result will be terminated with a nul byte.

Note that the input is expected to be already in native endianness, an initial byte-order-mark character is not handled specially. convert can be used to convert a byte buffer of UTF-16 data of ambiguous endianness.

Further note that this function does not validate the result string; it may (for example) include embedded nul characters. The only validation done by this function is to ensure that the input can be correctly interpreted as UTF-16, i.e. it doesn’t contain unpaired surrogates or partial character sequences.

Parameters:

  • str — a UTF-16 encoded string

utf8_casefold

def utf8_casefold(str: str, len: int) -> str

Converts a string into a form that is independent of case. The result will not correspond to any particular case, but can be compared for equality or ordered with the results of calling utf8_casefold on other strings.

Note that calling utf8_casefold followed by utf8_collate is only an approximation to the correct linguistic case insensitive ordering, though it is a fairly good one. Getting this exactly right would require a more sophisticated collation function that takes case sensitivity into account. GLib does not currently provide such a function.

Parameters:

  • str — a UTF-8 encoded string
  • len — length of str, in bytes, or -1 if str is nul-terminated.

utf8_collate

def utf8_collate(str1: str, str2: str) -> int

Compares two strings for ordering using the linguistically correct rules for the current locale. When sorting a large number of strings, it will be significantly faster to obtain collation keys with utf8_collate_key and compare the keys with strcmp() when sorting instead of sorting the original strings.

If the two strings are not comparable due to being in different collation sequences, the result is undefined. This can happen if the strings are in different language scripts, for example.

Parameters:

  • str1 — a UTF-8 encoded string
  • str2 — a UTF-8 encoded string

utf8_collate_key

def utf8_collate_key(str: str, len: int) -> str

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

The results of comparing the collation keys of two strings with strcmp() will always be the same as comparing the two original keys with utf8_collate.

Note that this function depends on the current locale.

Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.

Parameters:

  • str — a UTF-8 encoded string.
  • len — length of str, in bytes, or -1 if str is nul-terminated.

utf8_collate_key_for_filename

def utf8_collate_key_for_filename(str: str, len: int) -> str

Converts a string into a collation key that can be compared with other collation keys produced by the same function using strcmp().

In order to sort filenames correctly, this function treats the dot '.' as a special case. Most dictionary orderings seem to consider it insignificant, thus producing the ordering "event.c" "eventgenerator.c" "event.h" instead of "event.c" "event.h" "eventgenerator.c". Also, we would like to treat numbers intelligently so that "file1" "file10" "file5" is sorted as "file1" "file5" "file10".

Note that this function depends on the current locale.

Note that the returned string is not guaranteed to be in any encoding, especially UTF-8. The returned value is meant to be used only for comparisons.

Parameters:

  • str — a UTF-8 encoded string.
  • len — length of str, in bytes, or -1 if str is nul-terminated.

utf8_find_next_char

def utf8_find_next_char(p: str, end: str | None = ...) -> str | None

Finds the start of the next UTF-8 character in the string after p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

If end is NULL, the return value will never be NULL: if the end of the string is reached, a pointer to the terminating nul byte is returned. If end is non-NULL, the return value will be NULL if the end of the string is reached.

Parameters:

  • p — a pointer to a position within a UTF-8 encoded string
  • end — a pointer to the byte following the end of the string, or NULL to indicate that the string is nul-terminated

utf8_find_prev_char

def utf8_find_prev_char(str: str, p: str) -> str | None

Given a position p with a UTF-8 encoded string str, find the start of the previous UTF-8 character starting before p. Returns NULL if no UTF-8 characters are present in str before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte.

Parameters:

  • str — pointer to the beginning of a UTF-8 encoded string
  • p — pointer to some position within str

utf8_get_char

def utf8_get_char(p: str) -> str

Converts a sequence of bytes encoded as UTF-8 to a Unicode character.

If p does not point to a valid UTF-8 encoded character, results are undefined. If you are not sure that the bytes are complete valid Unicode characters, you should use utf8_get_char_validated instead.

Parameters:

  • p — a pointer to Unicode character encoded as UTF-8

utf8_get_char_validated

def utf8_get_char_validated(p: str, max_len: int) -> str

Convert a sequence of bytes encoded as UTF-8 to a Unicode character.

This function checks for incomplete characters, for invalid characters such as characters that are out of the range of Unicode, and for overlong encodings of valid characters.

Note that utf8_get_char_validated returns (gunichar)-2 if max_len is positive and any of the bytes in the first UTF-8 character sequence are nul.

Parameters:

  • p — a pointer to Unicode character encoded as UTF-8
  • max_len — the maximum number of bytes to read, or -1 if p is nul-terminated

utf8_make_valid

def utf8_make_valid(str: str, len: int) -> str

If the provided string is valid UTF-8, return a copy of it. If not, return a copy in which bytes that could not be interpreted as valid Unicode are replaced with the Unicode replacement character (U+FFFD).

For example, this is an appropriate function to use if you have received a string that was incorrectly declared to be UTF-8, and you need a valid UTF-8 version of it that can be logged or displayed to the user, with the assumption that it is close enough to ASCII or UTF-8 to be mostly readable as-is.

Parameters:

  • str — string to coerce into UTF-8
  • len — the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.

utf8_normalize

def utf8_normalize(str: str, len: int, mode: NormalizeMode | int) -> str | None

Converts a string into canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. The string has to be valid UTF-8, otherwise None is returned. You should generally call utf8_normalize before comparing two Unicode strings.

The normalization mode NormalizeMode.DEFAULT only standardizes differences that do not affect the text content, such as the above-mentioned accent representation. NormalizeMode.ALL also standardizes the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same.

NormalizeMode.DEFAULT_COMPOSE and NormalizeMode.ALL_COMPOSE are like NormalizeMode.DEFAULT and NormalizeMode.ALL, but returned a result with composed forms rather than a maximally decomposed form. This is often useful if you intend to convert the string to a legacy encoding or pass it to a system with less capable Unicode handling.

Parameters:

  • str — a UTF-8 encoded string.
  • len — length of str, in bytes, or -1 if str is nul-terminated.
  • mode — the type of normalization to perform.

utf8_offset_to_pointer

def utf8_offset_to_pointer(str: str, offset: int) -> str

Converts from an integer character offset to a pointer to a position within the string.

Since 2.10, this function allows to pass a negative offset to step backwards. It is usually worth stepping backwards from the end instead of forwards if offset is in the last fourth of the string, since moving forward is about 3 times faster than moving backward.

Note that this function doesn’t abort when reaching the end of str. Therefore you should be sure that offset is within string boundaries before calling that function. Call utf8_strlen when unsure. This limitation exists as this function is called frequently during text rendering and therefore has to be as fast as possible.

Parameters:

  • str — a UTF-8 encoded string
  • offset — a character offset within str

utf8_pointer_to_offset

def utf8_pointer_to_offset(str: str, pos: str) -> int

Converts from a pointer to position within a string to an integer character offset.

Since 2.10, this function allows pos to be before str, and returns a negative offset in this case.

Parameters:

  • str — a UTF-8 encoded string
  • pos — a pointer to a position within str

utf8_prev_char

def utf8_prev_char(p: str) -> str

Finds the previous UTF-8 character in the string before p.

p does not have to be at the beginning of a UTF-8 character. No check is made to see if the character found is actually valid other than it starts with an appropriate byte. If p might be the first character of the string, you must use utf8_find_prev_char instead.

Parameters:

  • p — a pointer to a position within a UTF-8 encoded string

utf8_strchr

def utf8_strchr(p: str, len: int, c: str) -> str | None

Finds the leftmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes.

If len is -1, allow unbounded search.

Parameters:

  • p — a nul-terminated UTF-8 encoded string
  • len — the maximum length of p
  • c — a Unicode character

utf8_strdown

def utf8_strdown(str: str, len: int) -> str

Converts all Unicode characters in the string that have a case to lowercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string changing.

Parameters:

  • str — a UTF-8 encoded string
  • len — length of str, in bytes, or -1 if str is nul-terminated.

utf8_strlen

def utf8_strlen(p: str, max: int) -> int

Computes the length of the string in characters, not including the terminating nul character. If the max’th byte falls in the middle of a character, the last (partial) character is not counted.

Parameters:

  • p — pointer to the start of a UTF-8 encoded string
  • max — the maximum number of bytes to examine. If max is less than 0, then the string is assumed to be nul-terminated. If max is 0, p will not be examined and may be NULL. If max is greater than 0, up to max bytes are examined

utf8_strncpy

def utf8_strncpy(dest: str, src: str, n: int) -> str

Like the standard C strncpy() function, but copies a given number of characters instead of a given number of bytes.

The src string must be valid UTF-8 encoded text. (Use utf8_validate on all text before trying to use UTF-8 utility functions with it.)

Note you must ensure dest is at least 4 * n + 1 to fit the largest possible UTF-8 characters

Parameters:

  • dest — buffer to fill with characters from src
  • src — UTF-8 encoded string
  • n — character count

utf8_strrchr

def utf8_strrchr(p: str, len: int, c: str) -> str | None

Find the rightmost occurrence of the given Unicode character in a UTF-8 encoded string, while limiting the search to len bytes.

If len is -1, allow unbounded search.

Parameters:

  • p — a nul-terminated UTF-8 encoded string
  • len — the maximum length of p
  • c — a Unicode character

utf8_strreverse

def utf8_strreverse(str: str, len: int) -> str

Reverses a UTF-8 string.

str must be valid UTF-8 encoded text. (Use utf8_validate on all text before trying to use UTF-8 utility functions with it.)

This function is intended for programmatic uses of reversed strings. It pays no attention to decomposed characters, combining marks, byte order marks, directional indicators (LRM, LRO, etc) and similar characters which might need special handling when reversing a string for display purposes.

Note that unlike strreverse, this function returns newly-allocated memory, which should be freed with free when no longer needed.

Parameters:

  • str — a UTF-8 encoded string
  • len — the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.

utf8_strup

def utf8_strup(str: str, len: int) -> str

Converts all Unicode characters in the string that have a case to uppercase. The exact manner that this is done depends on the current locale, and may result in the number of characters in the string increasing. (For instance, the German ess-zet will be changed to SS.)

Parameters:

  • str — a UTF-8 encoded string
  • len — length of str, in bytes, or -1 if str is nul-terminated.

utf8_substring

def utf8_substring(str: str, start_pos: int, end_pos: int) -> str

Copies a substring out of a UTF-8 encoded string. The substring will contain end_pos - start_pos characters.

Since GLib 2.72, -1 can be passed to end_pos to indicate the end of the string.

Parameters:

  • str — a UTF-8 encoded string
  • start_pos — a character offset within str
  • end_pos — another character offset within str, or -1 to indicate the end of the string

utf8_to_ucs4

def utf8_to_ucs4(str: str, len: int) -> tuple[str, int, int]

Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4.

A trailing nul character (U+0000) will be added to the string after the converted text.

Parameters:

  • str — a UTF-8 encoded string
  • len — the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.

utf8_to_ucs4_fast

def utf8_to_ucs4_fast(str: str, len: int) -> tuple[str, int]

Convert a string from UTF-8 to a 32-bit fixed width representation as UCS-4, assuming valid UTF-8 input.

This function is roughly twice as fast as utf8_to_ucs4 but does no error checking on the input. A trailing nul character (U+0000) will be added to the string after the converted text.

Parameters:

  • str — a UTF-8 encoded string
  • len — the maximum length of str to use, in bytes. If len is negative, then the string is nul-terminated.

utf8_to_utf16

def utf8_to_utf16(str: str, len: int) -> tuple[int, int, int]

Convert a string from UTF-8 to UTF-16.

A nul character (U+0000) will be added to the result after the converted text.

Parameters:

  • str — a UTF-8 encoded string
  • len — the maximum length (number of bytes) of str to use. If len is negative, then the string is nul-terminated.

utf8_truncate_middle

def utf8_truncate_middle(string: str, truncate_length: int) -> str

Cuts off the middle of the string, preserving half of truncate_length characters at the beginning and half at the end.

If string is already short enough, this returns a copy of string. If truncate_length is 0, an empty string is returned.

Parameters:

  • string — a nul-terminated UTF-8 encoded string
  • truncate_length — the new size of string, in characters, including the ellipsis character

utf8_validate

def utf8_validate(str: list[int]) -> tuple[bool, list[int]]

Validates UTF-8 encoded text.

str is the text to validate; if str is nul-terminated, then max_len can be -1, otherwise max_len should be the number of bytes to validate.

If end is non-NULL, then the end of the valid range will be stored there. This is the first byte of the first invalid character if some bytes were invalid, or the end of the text being validated otherwise — either the trailing nul byte, or the first byte beyond max_len (if it’s positive).

Note that g_utf8_validate() returns FALSE if max_len is positive and any of the max_len bytes are nul.

Returns TRUE if all of str was valid. Many GLib and GTK routines require valid UTF-8 as input; so data read from a file or the network should be checked with g_utf8_validate() before doing anything else with it.

Parameters:

  • str — a pointer to character data

utf8_validate_len

def utf8_validate_len(str: list[int]) -> tuple[bool, list[int]]

Validates UTF-8 encoded text.

As with utf8_validate, but max_len must be set, and hence this function will always return FALSE if any of the bytes of str are nul.

Parameters:

  • str — a pointer to character data

utime

def utime(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], utb: int | None = ...) -> int

A wrapper for the POSIX utime() function. The utime() function sets the access and modification timestamps of a file.

See your C library manual for more details about how utime() works on your system.

Parameters:

  • filename — a pathname in the GLib file name encoding (UTF-8 on Windows)
  • utb — a pointer to a struct utimbuf.

uuid_string_is_valid

def uuid_string_is_valid(str: str) -> bool

Parses the string str and verify if it is a UUID.

The function accepts the following syntax:

  • simple forms (e.g. f81d4fae-7dec-11d0-a765-00a0c91e6bf6)

Note that hyphens are required within the UUID string itself, as per the aforementioned RFC.

Parameters:

  • str — a string representing a UUID

uuid_string_random

def uuid_string_random() -> str

Generates a random UUID (RFC 4122 version 4) as a string. It has the same randomness guarantees as Rand, so must not be used for cryptographic purposes such as key generation, nonces, salts or one-time pads.

variant_get_gtype

def variant_get_gtype() -> type | GObject.Type

Enumerations

AsciiType

Bit flags.

  • ALNUM = 1
  • ALPHA = 2
  • CNTRL = 4
  • DIGIT = 8
  • GRAPH = 16
  • LOWER = 32
  • PRINT = 64
  • PUNCT = 128
  • SPACE = 256
  • UPPER = 512
  • XDIGIT = 1024

BookmarkFileError

Enumeration.

  • INVALID_URI = 0 — URI was ill-formed
  • INVALID_VALUE = 1 — a requested field was not found
  • APP_NOT_REGISTERED = 2 — a requested application did not register a bookmark
  • URI_NOT_FOUND = 3 — a requested URI was not found
  • READ = 4 — document was ill formed
  • UNKNOWN_ENCODING = 5 — the text being parsed was in an unknown encoding
  • WRITE = 6 — an error occurred while writing
  • FILE_NOT_FOUND = 7 — requested file was not found

ChecksumType

Enumeration.

  • MD5 = 0 — Use the MD5 hashing algorithm
  • SHA1 = 1 — Use the SHA-1 hashing algorithm
  • SHA256 = 2 — Use the SHA-256 hashing algorithm
  • SHA512 = 3 — Use the SHA-512 hashing algorithm (Since: 2.36)
  • SHA384 = 4 — Use the SHA-384 hashing algorithm (Since: 2.51)

ConvertError

Enumeration.

  • NO_CONVERSION = 0 — Conversion between the requested character sets is not supported.
  • ILLEGAL_SEQUENCE = 1 — Invalid byte sequence in conversion input; or the character sequence could not be represented in the target character set.
  • FAILED = 2 — Conversion failed for some reason.
  • PARTIAL_INPUT = 3 — Partial character sequence at end of input.
  • BAD_URI = 4 — URI is invalid.
  • NOT_ABSOLUTE_PATH = 5 — Pathname is not an absolute path.
  • NO_MEMORY = 6 — No memory available. Since: 2.40
  • EMBEDDED_NUL = 7 — An embedded NUL character is present in conversion output where a NUL-terminated string is expected. Since: 2.56

DateDMY

Enumeration.

  • DAY = 0 — a day
  • MONTH = 1 — a month
  • YEAR = 2 — a year

DateMonth

Enumeration.

  • BAD_MONTH = 0 — invalid value
  • JANUARY = 1 — January
  • FEBRUARY = 2 — February
  • MARCH = 3 — March
  • APRIL = 4 — April
  • MAY = 5 — May
  • JUNE = 6 — June
  • JULY = 7 — July
  • AUGUST = 8 — August
  • SEPTEMBER = 9 — September
  • OCTOBER = 10 — October
  • NOVEMBER = 11 — November
  • DECEMBER = 12 — December

DateWeekday

Enumeration.

  • BAD_WEEKDAY = 0 — invalid value
  • MONDAY = 1 — Monday
  • TUESDAY = 2 — Tuesday
  • WEDNESDAY = 3 — Wednesday
  • THURSDAY = 4 — Thursday
  • FRIDAY = 5 — Friday
  • SATURDAY = 6 — Saturday
  • SUNDAY = 7 — Sunday

ErrorType

Enumeration.

  • UNKNOWN = 0 — unknown error
  • UNEXP_EOF = 1 — unexpected end of file
  • UNEXP_EOF_IN_STRING = 2 — unterminated string constant
  • UNEXP_EOF_IN_COMMENT = 3 — unterminated comment
  • NON_DIGIT_IN_CONST = 4 — non-digit character in a number
  • DIGIT_RADIX = 5 — digit beyond radix in a number
  • FLOAT_RADIX = 6 — non-decimal floating point number
  • FLOAT_MALFORMED = 7 — malformed floating point number

FileError

Enumeration.

  • EXIST = 0 — Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.
  • ISDIR = 1 — File is a directory; you cannot open a directory for writing, or create or remove hard links to it.
  • ACCES = 2 — Permission denied; the file permissions do not allow the attempted operation.
  • NAMETOOLONG = 3 — Filename too long.
  • NOENT = 4 — No such file or directory. This is a "file doesn't exist" error for ordinary files that are referenced in contexts where they are expected to already exist.
  • NOTDIR = 5 — A file that isn't a directory was specified when a directory is required.
  • NXIO = 6 — No such device or address. The system tried to use the device represented by a file you specified, and it couldn't find the device. This can mean that the device file was installed incorrectly, or that the physical device is missing or not correctly attached to the computer.
  • NODEV = 7 — The underlying file system of the specified file does not support memory mapping.
  • ROFS = 8 — The directory containing the new link can't be modified because it's on a read-only file system.
  • TXTBSY = 9 — Text file busy.
  • FAULT = 10 — You passed in a pointer to bad memory. (GLib won't reliably return this, don't pass in pointers to bad memory.)
  • LOOP = 11 — Too many levels of symbolic links were encountered in looking up a file name. This often indicates a cycle of symbolic links.
  • NOSPC = 12 — No space left on device; write operation on a file failed because the disk is full.
  • NOMEM = 13 — No memory available. The system cannot allocate more virtual memory because its capacity is full.
  • MFILE = 14 — The current process has too many files open and can't open any more. Duplicate descriptors do count toward this limit.
  • NFILE = 15 — There are too many distinct file openings in the entire system.
  • BADF = 16 — Bad file descriptor; for example, I/O on a descriptor that has been closed or reading from a descriptor open only for writing (or vice versa).
  • INVAL = 17 — Invalid argument. This is used to indicate various kinds of problems with passing the wrong argument to a library function.
  • PIPE = 18 — Broken pipe; there is no process reading from the other end of a pipe. Every library function that returns this error code also generates a 'SIGPIPE' signal; this signal terminates the program if not handled or blocked. Thus, your program will never actually see this code unless it has handled or blocked 'SIGPIPE'.
  • AGAIN = 19 — Resource temporarily unavailable; the call might work if you try again later.
  • INTR = 20 — Interrupted function call; an asynchronous signal occurred and prevented completion of the call. When this happens, you should try the call again.
  • IO = 21 — Input/output error; usually used for physical read or write errors. i.e. the disk or other physical device hardware is returning errors.
  • PERM = 22 — Operation not permitted; only the owner of the file (or other resource) or processes with special privileges can perform the operation.
  • NOSYS = 23 — Function not implemented; this indicates that the system is missing some functionality.
  • FAILED = 24 — Does not correspond to a UNIX error code; this is the standard "failed for unspecified reason" error code present in all Error error code enumerations. Returned if no specific code applies.

FileSetContentsFlags

Bit flags.

  • NONE = 0 — No guarantees about file consistency or durability. The most dangerous setting, which is slightly faster than other settings.
  • CONSISTENT = 1 — Guarantee file consistency: after a crash, either the old version of the file or the new version of the file will be available, but not a mixture. On Unix systems this equates to an fsync() on the file and use of an atomic rename() of the new version of the file over the old.
  • DURABLE = 2 — Guarantee file durability: after a crash, the new version of the file will be available. On Unix systems this equates to an fsync() on the file (if FileSetContentsFlags.CONSISTENT is unset), or the effects of FileSetContentsFlags.CONSISTENT plus an fsync() on the directory containing the file after calling rename().
  • ONLY_EXISTING = 4 — Only apply consistency and durability guarantees if the file already exists. This may speed up file operations if the file doesn’t currently exist, but may result in a corrupted version of the new file if the system crashes while writing it.

FileTest

Bit flags.

  • IS_REGULAR = 1True if the file is a regular file (not a directory). Note that this test will also return True if the tested file is a symlink to a regular file.
  • IS_SYMLINK = 2True if the file is a symlink.
  • IS_DIR = 4True if the file is a directory.
  • IS_EXECUTABLE = 8True if the file is executable.
  • EXISTS = 16True if the file exists. It may or may not be a regular file.

FormatSizeFlags

Bit flags.

  • DEFAULT = 0 — behave the same as format_size
  • LONG_FORMAT = 1 — include the exact number of bytes as part of the returned string. For example, "45.6 kB (45,612 bytes)".
  • IEC_UNITS = 2 — use IEC (base 1024) units with "KiB"-style suffixes. IEC units should only be used for reporting things with a strong "power of 2" basis, like RAM sizes or RAID stripe sizes. Network and storage sizes should be reported in the normal SI units.
  • BITS = 4 — set the size as a quantity in bits, rather than bytes, and return units in bits. For example, ‘Mbit’ rather than ‘MB’.
  • ONLY_VALUE = 8 — return only value, without unit; this should not be used together with G_FORMAT_SIZE_LONG_FORMAT nor G_FORMAT_SIZE_ONLY_UNIT. Since: 2.74
  • ONLY_UNIT = 16 — return only unit, without value; this should not be used together with G_FORMAT_SIZE_LONG_FORMAT nor G_FORMAT_SIZE_ONLY_VALUE. Since: 2.74

HookFlagMask

Bit flags.

  • ACTIVE = 1 — set if the hook has not been destroyed
  • IN_CALL = 2 — set if the hook is currently being run
  • RESERVED1 = 4

IOChannelError

Enumeration.

  • FBIG = 0 — File too large.
  • INVAL = 1 — Invalid argument.
  • IO = 2 — IO error.
  • ISDIR = 3 — File is a directory.
  • NOSPC = 4 — No space left on device.
  • NXIO = 5 — No such device or address.
  • OVERFLOW = 6 — Value too large for defined datatype.
  • PIPE = 7 — Broken pipe.
  • FAILED = 8 — Some other error.

IOCondition

Bit flags.

  • IN = 1 — There is data to read.
  • OUT = 4 — Data can be written (without blocking).
  • PRI = 2 — There is urgent data to read.
  • ERR = 8 — Error condition.
  • HUP = 16 — Hung up (the connection has been broken, usually for pipes and sockets).
  • NVAL = 32 — Invalid request. The file descriptor is not open.

IOError

Enumeration.

  • NONE = 0 — no error
  • AGAIN = 1 — an EAGAIN error occurred
  • INVAL = 2 — an EINVAL error occurred
  • UNKNOWN = 3 — another error occurred

IOFlags

Bit flags.

  • NONE = 0 — no special flags set. Since: 2.74
  • APPEND = 1 — turns on append mode, corresponds to O_APPEND (see the documentation of the UNIX open() syscall)
  • NONBLOCK = 2 — turns on nonblocking mode, corresponds to O_NONBLOCK/O_NDELAY (see the documentation of the UNIX open() syscall)
  • IS_READABLE = 4 — indicates that the io channel is readable. This flag cannot be changed.
  • IS_WRITABLE = 8 — indicates that the io channel is writable. This flag cannot be changed.
  • IS_WRITEABLE = 8 — a misspelled version of G_IO_FLAG_IS_WRITABLE that existed before the spelling was fixed in GLib 2.30. It is kept here for compatibility reasons. Deprecated since 2.30
  • IS_SEEKABLE = 16 — indicates that the io channel is seekable, i.e. that IOChannel.seek_position can be used on it. This flag cannot be changed.
  • MASK = 31 — the mask that specifies all the valid flags.
  • GET_MASK = 31 — the mask of the flags that are returned from IOChannel.get_flags
  • SET_MASK = 3 — the mask of the flags that the user can modify with IOChannel.set_flags

IOStatus

Enumeration.

  • ERROR = 0 — An error occurred.
  • NORMAL = 1 — Success.
  • EOF = 2 — End of file.
  • AGAIN = 3 — Resource temporarily unavailable.

KeyFileError

Enumeration.

  • UNKNOWN_ENCODING = 0 — the text being parsed was in an unknown encoding
  • PARSE = 1 — document was ill-formed
  • NOT_FOUND = 2 — the file was not found
  • KEY_NOT_FOUND = 3 — a requested key was not found
  • GROUP_NOT_FOUND = 4 — a requested group was not found
  • INVALID_VALUE = 5 — a value could not be parsed

KeyFileFlags

Bit flags.

  • NONE = 0 — No flags, default behaviour
  • KEEP_COMMENTS = 1 — Use this flag if you plan to write the (possibly modified) contents of the key file back to a file; otherwise all comments will be lost when the key file is written back.
  • KEEP_TRANSLATIONS = 2 — Use this flag if you plan to write the (possibly modified) contents of the key file back to a file; otherwise only the translations for the current language will be written back.

LogLevelFlags

Bit flags.

  • FLAG_RECURSION = 1 — internal flag
  • FLAG_FATAL = 2 — internal flag
  • LEVEL_ERROR = 4 — log level for errors, see GLib.error. This level is also used for messages produced by GLib.assert.
  • LEVEL_CRITICAL = 8 — log level for critical warning messages, see GLib.critical. This level is also used for messages produced by GLib.return_if_fail and GLib.return_val_if_fail.
  • LEVEL_WARNING = 16 — log level for warnings, see GLib.warning
  • LEVEL_MESSAGE = 32 — log level for messages, see GLib.message
  • LEVEL_INFO = 64 — log level for informational messages, see GLib.info
  • LEVEL_DEBUG = 128 — log level for debug messages, see GLib.debug
  • LEVEL_MASK = -4 — a mask including all log levels

LogWriterOutput

Enumeration.

  • HANDLED = 1 — Log writer has handled the log entry.
  • UNHANDLED = 0 — Log writer could not handle the log entry.

MainContextFlags

Bit flags.

  • NONE = 0 — Default behaviour.
  • OWNERLESS_POLLING = 1 — Assume that polling for events will free the thread to process other jobs. That's useful if you're using g_main_context_{prepare,query,check,dispatch} to integrate GMainContext in other event loops.

MarkupCollectType

Bit flags.

  • INVALID = 0 — used to terminate the list of attributes to collect
  • STRING = 1 — collect the string pointer directly from the attribute_values[] array. Expects a parameter of type (const char **). If MarkupCollectType.OPTIONAL is specified and the attribute isn't present then the pointer will be set to None
  • STRDUP = 2 — as with MarkupCollectType.STRING, but expects a parameter of type (char **) and strdups the returned pointer. The pointer must be freed with free
  • BOOLEAN = 3 — expects a parameter of type (gboolean *) and parses the attribute value as a boolean. Sets False if the attribute isn't present. Valid boolean values consist of (case-insensitive) "false", "f", "no", "n", "0" and "true", "t", "yes", "y", "1"
  • TRISTATE = 4 — as with MarkupCollectType.BOOLEAN, but in the case of a missing attribute a value is set that compares equal to neither False nor True MarkupCollectType.OPTIONAL is implied
  • OPTIONAL = 65536 — can be bitwise ORed with the other fields. If present, allows the attribute not to appear. A default value is set depending on what value type is used

MarkupError

Enumeration.

  • BAD_UTF8 = 0 — text being parsed was not valid UTF-8
  • EMPTY = 1 — document contained nothing, or only whitespace
  • PARSE = 2 — document was ill-formed
  • UNKNOWN_ELEMENT = 3 — error should be set by MarkupParser functions; element wasn't known
  • UNKNOWN_ATTRIBUTE = 4 — error should be set by MarkupParser functions; attribute wasn't known
  • INVALID_CONTENT = 5 — error should be set by MarkupParser functions; content was invalid
  • MISSING_ATTRIBUTE = 6 — error should be set by MarkupParser functions; a required attribute was missing

MarkupParseFlags

Bit flags.

  • DEFAULT_FLAGS = 0 — No special behaviour. Since: 2.74
  • DO_NOT_USE_THIS_UNSUPPORTED_FLAG = 1 — flag you should not use
  • TREAT_CDATA_AS_TEXT = 2 — When this flag is set, CDATA marked sections are not passed literally to the passthrough function of the parser. Instead, the content of the section (without the <![CDATA[ and ]]>) is passed to the text function. This flag was added in GLib 2.12
  • PREFIX_ERROR_POSITION = 4 — Normally errors caught by GMarkup itself have line/column information prefixed to them to let the caller know the location of the error. When this flag is set the location information is also prefixed to errors generated by the MarkupParser implementation functions
  • IGNORE_QUALIFIED = 8 — Ignore (don't report) qualified attributes and tags, along with their contents. A qualified attribute or tag is one that contains ':' in its name (ie: is in another namespace). Since: 2.40.

NormalizeMode

Enumeration.

  • DEFAULT = 0 — standardize differences that do not affect the text content, such as the above-mentioned accent representation
  • NFD = 0 — another name for NormalizeMode.DEFAULT
  • DEFAULT_COMPOSE = 1 — like NormalizeMode.DEFAULT, but with composed forms rather than a maximally decomposed form
  • NFC = 1 — another name for NormalizeMode.DEFAULT_COMPOSE
  • ALL = 2 — beyond NormalizeMode.DEFAULT also standardize the "compatibility" characters in Unicode, such as SUPERSCRIPT THREE to the standard forms (in this case DIGIT THREE). Formatting information may be lost but for most text operations such characters should be considered the same
  • NFKD = 2 — another name for NormalizeMode.ALL
  • ALL_COMPOSE = 3 — like NormalizeMode.ALL, but with composed forms rather than a maximally decomposed form
  • NFKC = 3 — another name for NormalizeMode.ALL_COMPOSE

NumberParserError

Enumeration.

  • INVALID = 0 — string was not a valid number
  • OUT_OF_BOUNDS = 1 — string was a number, but out of bounds

OnceStatus

Enumeration.

  • NOTCALLED = 0 — the function has not been called yet.
  • PROGRESS = 1 — the function call is currently in progress.
  • READY = 2 — the function has been called.

OptionArg

Enumeration.

  • NONE = 0 — No extra argument. This is useful for simple flags or booleans.
  • STRING = 1 — The option takes a UTF-8 string argument.
  • INT = 2 — The option takes an integer argument.
  • CALLBACK = 3 — The option provides a callback (of type GOptionArgFunc) to parse the extra argument.
  • FILENAME = 4 — The option takes a filename as argument, which will be in the GLib filename encoding rather than UTF-8.
  • STRING_ARRAY = 5 — The option takes a string argument, multiple uses of the option are collected into an array of strings.
  • FILENAME_ARRAY = 6 — The option takes a filename as argument, multiple uses of the option are collected into an array of strings.
  • DOUBLE = 7 — The option takes a double argument. The argument can be formatted either for the user's locale or for the "C" locale. Since 2.12
  • INT64 = 8 — The option takes a 64-bit integer. Like OptionArg.INT but for larger numbers. The number can be in decimal base, or in hexadecimal (when prefixed with 0x, for example, 0xffffffff). Since 2.12

OptionError

Enumeration.

  • UNKNOWN_OPTION = 0 — An option was not known to the parser. This error will only be reported, if the parser hasn't been instructed to ignore unknown options, see OptionContext.set_ignore_unknown_options.
  • BAD_VALUE = 1 — A value couldn't be parsed.
  • FAILED = 2 — A GOptionArgFunc callback failed.

OptionFlags

Bit flags.

  • NONE = 0 — No flags.
  • HIDDEN = 1 — The option doesn't appear in --help output.
  • IN_MAIN = 2 — The option appears in the main section of the --help output, even if it is defined in a group.
  • REVERSE = 4 — For options of the OptionArg.NONE kind, this flag indicates that the sense of the option is reversed. i.e. False will be stored into the argument rather than True.
  • NO_ARG = 8 — For options of the OptionArg.CALLBACK kind, this flag indicates that the callback does not take any argument (like a OptionArg.NONE option). Since 2.8
  • FILENAME = 16 — For options of the OptionArg.CALLBACK kind, this flag indicates that the argument should be passed to the callback in the GLib filename encoding rather than UTF-8. Since 2.8
  • OPTIONAL_ARG = 32 — For options of the OptionArg.CALLBACK kind, this flag indicates that the argument supply is optional. If no argument is given then data of GOptionParseFunc will be set to NULL. Since 2.8
  • NOALIAS = 64 — This flag turns off the automatic conflict resolution which prefixes long option names with groupname- if there is a conflict. This option should only be used in situations where aliasing is necessary to model some legacy commandline interface. It is not safe to use this option, unless all option groups are under your direct control. Since 2.8.
  • DEPRECATED = 128 — This flag marks the option as deprecated in the --help. You should update the description of the option to describe what the user should do in response to the deprecation, for instance: remove the option, or replace it with another one.

RegexCompileFlags

Bit flags.

  • DEFAULT = 0 — No special options set. Since: 2.74
  • CASELESS = 1 — Letters in the pattern match both upper- and lowercase letters. This option can be changed within a pattern by a "(?i)" option setting.
  • MULTILINE = 2 — By default, GRegex treats the strings as consisting of a single line of characters (even if it actually contains newlines). The "start of line" metacharacter ("^") matches only at the start of the string, while the "end of line" metacharacter ("$") matches only at the end of the string, or before a terminating newline (unless RegexCompileFlags.DOLLAR_ENDONLY is set). When RegexCompileFlags.MULTILINE is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the string, respectively, as well as at the very start and end. This can be changed within a pattern by a "(?m)" option setting.
  • DOTALL = 4 — A dot metacharacter (".") in the pattern matches all characters, including newlines. Without it, newlines are excluded. This option can be changed within a pattern by a ("?s") option setting.
  • EXTENDED = 8 — Whitespace data characters in the pattern are totally ignored except when escaped or inside a character class. Whitespace does not include the VT character (code 11). In addition, characters between an unescaped "#" outside a character class and the next newline character, inclusive, are also ignored. This can be changed within a pattern by a "(?x)" option setting.
  • ANCHORED = 16 — The pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string that is being searched. This effect can also be achieved by appropriate constructs in the pattern itself such as the "^" metacharacter.
  • DOLLAR_ENDONLY = 32 — A dollar metacharacter ("$") in the pattern matches only at the end of the string. Without this option, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This option is ignored if RegexCompileFlags.MULTILINE is set.
  • UNGREEDY = 512 — Inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It can also be set by a "(?U)" option setting within the pattern.
  • RAW = 2048 — Usually strings must be valid UTF-8 strings, using this flag they are considered as a raw sequence of bytes.
  • NO_AUTO_CAPTURE = 4096 — Disables the use of numbered capturing parentheses in the pattern. Any opening parenthesis that is not followed by "?" behaves as if it were followed by "?:" but named parentheses can still be used for capturing (and they acquire numbers in the usual way).
  • OPTIMIZE = 8192 — Since 2.74 and the port to pcre2, requests JIT compilation, which, if the just-in-time compiler is available, further processes a compiled pattern into machine code that executes much faster. However, it comes at the cost of extra processing before the match is performed, so it is most beneficial to use this when the same compiled pattern is used for matching many times. Before 2.74 this option used the built-in non-JIT optimizations in pcre1.
  • FIRSTLINE = 262144 — Limits an unanchored pattern to match before (or at) the first newline. Since: 2.34
  • DUPNAMES = 524288 — Names used to identify capturing subpatterns need not be unique. This can be helpful for certain types of pattern when it is known that only one instance of the named subpattern can ever be matched.
  • NEWLINE_CR = 1048576 — Usually any newline character or character sequence is recognized. If this option is set, the only recognized newline character is '\r'.
  • NEWLINE_LF = 2097152 — Usually any newline character or character sequence is recognized. If this option is set, the only recognized newline character is '\n'.
  • NEWLINE_RESERVED1 = 4194304

RegexError

Enumeration.

  • COMPILE = 0 — Compilation of the regular expression failed.
  • OPTIMIZE = 1 — Optimization of the regular expression failed.
  • REPLACE = 2 — Replacement failed due to an ill-formed replacement string.
  • MATCH = 3 — The match process failed.
  • INTERNAL = 4 — Internal error of the regular expression engine. Since 2.16
  • STRAY_BACKSLASH = 101 — "\" at end of pattern. Since 2.16
  • MISSING_CONTROL_CHAR = 102 — "\c" at end of pattern. Since 2.16
  • UNRECOGNIZED_ESCAPE = 103 — Unrecognized character follows "\". Since 2.16
  • QUANTIFIERS_OUT_OF_ORDER = 104 — Numbers out of order in "{}" quantifier. Since 2.16
  • QUANTIFIER_TOO_BIG = 105 — Number too big in "{}" quantifier. Since 2.16
  • UNTERMINATED_CHARACTER_CLASS = 106 — Missing terminating "]" for character class. Since 2.16
  • INVALID_ESCAPE_IN_CHARACTER_CLASS = 107 — Invalid escape sequence in character class. Since 2.16
  • RANGE_OUT_OF_ORDER = 108 — Range out of order in character class. Since 2.16
  • NOTHING_TO_REPEAT = 109 — Nothing to repeat. Since 2.16
  • UNRECOGNIZED_CHARACTER = 112 — Unrecognized character after "(?", "(?<" or "(?P". Since 2.16
  • POSIX_NAMED_CLASS_OUTSIDE_CLASS = 113 — POSIX named classes are supported only within a class. Since 2.16
  • UNMATCHED_PARENTHESIS = 114 — Missing terminating ")" or ")" without opening "(". Since 2.16
  • INEXISTENT_SUBPATTERN_REFERENCE = 115 — Reference to non-existent subpattern. Since 2.16
  • UNTERMINATED_COMMENT = 118 — Missing terminating ")" after comment. Since 2.16
  • EXPRESSION_TOO_LARGE = 120 — Regular expression too large. Since 2.16
  • MEMORY_ERROR = 121 — Failed to get memory. Since 2.16
  • VARIABLE_LENGTH_LOOKBEHIND = 125 — Lookbehind assertion is not fixed length. Since 2.16
  • MALFORMED_CONDITION = 126 — Malformed number or name after "(?(". Since 2.16
  • TOO_MANY_CONDITIONAL_BRANCHES = 127 — Conditional group contains more than two branches. Since 2.16
  • ASSERTION_EXPECTED = 128 — Assertion expected after "(?(". Since 2.16
  • UNKNOWN_POSIX_CLASS_NAME = 130 — Unknown POSIX class name. Since 2.16
  • POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED = 131 — POSIX collating elements are not supported. Since 2.16
  • HEX_CODE_TOO_LARGE = 134 — Character value in "\x{...}" sequence is too large. Since 2.16
  • INVALID_CONDITION = 135 — Invalid condition "(?(0)". Since 2.16
  • SINGLE_BYTE_MATCH_IN_LOOKBEHIND = 136 — \C not allowed in lookbehind assertion. Since 2.16
  • INFINITE_LOOP = 140 — Recursive call could loop indefinitely. Since 2.16
  • MISSING_SUBPATTERN_NAME_TERMINATOR = 142 — Missing terminator in subpattern name. Since 2.16
  • DUPLICATE_SUBPATTERN_NAME = 143 — Two named subpatterns have the same name. Since 2.16
  • MALFORMED_PROPERTY = 146 — Malformed "\P" or "\p" sequence. Since 2.16
  • UNKNOWN_PROPERTY = 147 — Unknown property name after "\P" or "\p". Since 2.16
  • SUBPATTERN_NAME_TOO_LONG = 148 — Subpattern name is too long (maximum 32 characters). Since 2.16
  • TOO_MANY_SUBPATTERNS = 149 — Too many named subpatterns (maximum 10,000). Since 2.16
  • INVALID_OCTAL_VALUE = 151 — Octal value is greater than "\377". Since 2.16
  • TOO_MANY_BRANCHES_IN_DEFINE = 154 — "DEFINE" group contains more than one branch. Since 2.16
  • DEFINE_REPETION = 155 — Repeating a "DEFINE" group is not allowed. This error is never raised. Since: 2.16 Deprecated: 2.34
  • INCONSISTENT_NEWLINE_OPTIONS = 156 — Inconsistent newline options. Since 2.16
  • MISSING_BACK_REFERENCE = 157 — "\g" is not followed by a braced, angle-bracketed, or quoted name or number, or by a plain number. Since: 2.16
  • INVALID_RELATIVE_REFERENCE = 158 — relative reference must not be zero. Since: 2.34
  • BACKTRACKING_CONTROL_VERB_ARGUMENT_FORBIDDEN = 159 — the backtracing control verb used does not allow an argument. Since: 2.34
  • UNKNOWN_BACKTRACKING_CONTROL_VERB = 160 — unknown backtracing control verb. Since: 2.34
  • NUMBER_TOO_BIG = 161 — number is too big in escape sequence. Since: 2.34
  • MISSING_SUBPATTERN_NAME = 162 — Missing subpattern name. Since: 2.34
  • MISSING_DIGIT = 163 — Missing digit. Since 2.34
  • INVALID_DATA_CHARACTER = 164 — In JavaScript compatibility mode, "[" is an invalid data character. Since: 2.34
  • EXTRA_SUBPATTERN_NAME = 165 — different names for subpatterns of the same number are not allowed. Since: 2.34
  • BACKTRACKING_CONTROL_VERB_ARGUMENT_REQUIRED = 166 — the backtracing control verb requires an argument. Since: 2.34
  • INVALID_CONTROL_CHAR = 168 — "\c" must be followed by an ASCII character. Since: 2.34
  • MISSING_NAME = 169 — "\k" is not followed by a braced, angle-bracketed, or quoted name. Since: 2.34
  • NOT_SUPPORTED_IN_CLASS = 171 — "\N" is not supported in a class. Since: 2.34
  • TOO_MANY_FORWARD_REFERENCES = 172 — too many forward references. Since: 2.34
  • NAME_TOO_LONG = 175 — the name is too long in "(MARK)", "(PRUNE)", "(SKIP)", or "(THEN)". Since: 2.34
  • CHARACTER_VALUE_TOO_LARGE = 176 — the character value in the \u sequence is too large. Since: 2.34

RegexMatchFlags

Bit flags.

  • DEFAULT = 0 — No special options set. Since: 2.74
  • ANCHORED = 16 — The pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string that is being searched. This effect can also be achieved by appropriate constructs in the pattern itself such as the "^" metacharacter.
  • NOTBOL = 128 — Specifies that first character of the string is not the beginning of a line, so the circumflex metacharacter should not match before it. Setting this without RegexCompileFlags.MULTILINE (at compile time) causes circumflex never to match. This option affects only the behaviour of the circumflex metacharacter, it does not affect "\A".
  • NOTEOL = 256 — Specifies that the end of the subject string is not the end of a line, so the dollar metacharacter should not match it nor (except in multiline mode) a newline immediately before it. Setting this without RegexCompileFlags.MULTILINE (at compile time) causes dollar never to match. This option affects only the behaviour of the dollar metacharacter, it does not affect "\Z" or "\z".
  • NOTEMPTY = 1024 — An empty string is not considered to be a valid match if this option is set. If there are alternatives in the pattern, they are tried. If all the alternatives match the empty string, the entire match fails. For example, if the pattern "a?b?" is applied to a string not beginning with "a" or "b", it matches the empty string at the start of the string. With this flag set, this match is not valid, so GRegex searches further into the string for occurrences of "a" or "b".
  • PARTIAL = 32768 — Turns on the partial matching feature, for more documentation on partial matching see MatchInfo.is_partial_match.
  • NEWLINE_CR = 1048576 — Overrides the newline definition set when creating a new Regex, setting the '\r' character as line terminator.
  • NEWLINE_LF = 2097152 — Overrides the newline definition set when creating a new Regex, setting the '\n' character as line terminator.
  • NEWLINE_CRLF = 3145728 — Overrides the newline definition set when creating a new Regex, setting the '\r\n' characters sequence as line terminator.
  • NEWLINE_ANY = 4194304 — Overrides the newline definition set when creating a new Regex, any Unicode newline sequence is recognised as a newline. These are '\r', '\n' and '\rn', and the single characters U+000B LINE TABULATION, U+000C FORM FEED (FF), U+0085 NEXT LINE (NEL), U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR.
  • NEWLINE_ANYCRLF = 5242880 — Overrides the newline definition set when creating a new Regex; any '\r', '\n', or '\r\n' character sequence is recognized as a newline. Since: 2.34
  • BSR_ANYCRLF = 8388608 — Overrides the newline definition for "\R" set when creating a new Regex; only '\r', '\n', or '\r\n' character sequences are recognized as a newline by "\R". Since: 2.34
  • BSR_ANY = 16777216 — Overrides the newline definition for "\R" set when creating a new Regex; any Unicode newline character or character sequence are recognized as a newline by "\R". These are '\r', '\n' and '\rn', and the single characters U+000B LINE TABULATION, U+000C FORM FEED (FF), U+0085 NEXT LINE (NEL), U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR. Since: 2.34
  • PARTIAL_SOFT = 32768 — An alias for RegexMatchFlags.PARTIAL. Since: 2.34
  • PARTIAL_HARD = 134217728 — Turns on the partial matching feature. In contrast to to RegexMatchFlags.PARTIAL_SOFT, this stops matching as soon as a partial match is found, without continuing to search for a possible complete match. See MatchInfo.is_partial_match for more information. Since: 2.34
  • NOTEMPTY_ATSTART = 268435456 — Like RegexMatchFlags.NOTEMPTY, but only applied to the start of the matched string. For anchored patterns this can only happen for pattern containing "\K". Since: 2.34

SeekType

Enumeration.

  • CUR = 0 — the current position in the file.
  • SET = 1 — the start of the file.
  • END = 2 — the end of the file.

ShellError

Enumeration.

  • BAD_QUOTING = 0 — Mismatched or otherwise mangled quoting.
  • EMPTY_STRING = 1 — String to be parsed was empty.
  • FAILED = 2 — Some other error.

SliceConfig

Enumeration.

  • ALWAYS_MALLOC = 1
  • BYPASS_MAGAZINES = 2
  • WORKING_SET_MSECS = 3
  • COLOR_INCREMENT = 4
  • CHUNK_SIZES = 5
  • CONTENTION_COUNTER = 6

SpawnError

Enumeration.

  • FORK = 0 — Fork failed due to lack of memory.
  • READ = 1 — Read or select on pipes failed.
  • CHDIR = 2 — Changing to working directory failed.
  • ACCES = 3 — execv() returned EACCES
  • PERM = 4 — execv() returned EPERM
  • TOO_BIG = 5 — execv() returned E2BIG
  • _2BIG = 5 — deprecated alias for SpawnError.TOO_BIG (deprecated since GLib 2.32)
  • NOEXEC = 6 — execv() returned ENOEXEC
  • NAMETOOLONG = 7 — execv() returned ENAMETOOLONG
  • NOENT = 8 — execv() returned ENOENT
  • NOMEM = 9 — execv() returned ENOMEM
  • NOTDIR = 10 — execv() returned ENOTDIR
  • LOOP = 11 — execv() returned ELOOP
  • TXTBUSY = 12 — execv() returned ETXTBUSY
  • IO = 13 — execv() returned EIO
  • NFILE = 14 — execv() returned ENFILE
  • MFILE = 15 — execv() returned EMFILE
  • INVAL = 16 — execv() returned EINVAL
  • ISDIR = 17 — execv() returned EISDIR
  • LIBBAD = 18 — execv() returned ELIBBAD
  • FAILED = 19 — Some other fatal failure, error->message should explain.

SpawnFlags

Bit flags.

  • DEFAULT = 0 — no flags, default behaviour
  • LEAVE_DESCRIPTORS_OPEN = 1 — the parent's open file descriptors will be inherited by the child; otherwise all descriptors except stdin, stdout and stderr will be closed before calling exec() in the child.
  • DO_NOT_REAP_CHILD = 2 — the child will not be automatically reaped; you must use g_child_watch_add() yourself (or call waitpid() or handle SIGCHLD yourself), or the child will become a zombie.
  • SEARCH_PATH = 4argv[0] need not be an absolute path, it will be looked for in the user's PATH.
  • STDOUT_TO_DEV_NULL = 8 — the child's standard output will be discarded, instead of going to the same location as the parent's standard output.
  • STDERR_TO_DEV_NULL = 16 — the child's standard error will be discarded.
  • CHILD_INHERITS_STDIN = 32 — the child will inherit the parent's standard input (by default, the child's standard input is attached to /dev/null).
  • FILE_AND_ARGV_ZERO = 64 — the first element of argv is the file to execute, while the remaining elements are the actual argument vector to pass to the file. Normally spawn_async_with_pipes uses argv[0] as the file to execute, and passes all of argv to the child.
  • SEARCH_PATH_FROM_ENVP = 128 — if argv[0] is not an absolute path, it will be looked for in the PATH from the passed child environment. Since: 2.34
  • CLOEXEC_PIPES = 256 — create all pipes with the O_CLOEXEC flag set. Since: 2.40
  • CHILD_INHERITS_STDOUT = 512 — The child will inherit the parent's standard output.
  • CHILD_INHERITS_STDERR = 1024 — The child will inherit the parent's standard error.
  • STDIN_FROM_DEV_NULL = 2048 — The child's standard input is attached to /dev/null.

TestFileType

Enumeration.

  • DIST = 0 — a file that was included in the distribution tarball
  • BUILT = 1 — a file that was built on the compiling machine

TestLogType

Enumeration.

  • NONE = 0
  • ERROR = 1
  • START_BINARY = 2
  • LIST_CASE = 3
  • SKIP_CASE = 4
  • START_CASE = 5
  • STOP_CASE = 6
  • MIN_RESULT = 7
  • MAX_RESULT = 8
  • MESSAGE = 9
  • START_SUITE = 10
  • STOP_SUITE = 11

TestResult

Enumeration.

  • SUCCESS = 0
  • SKIPPED = 1
  • FAILURE = 2
  • INCOMPLETE = 3

TestSubprocessFlags

Bit flags.

  • DEFAULT = 0 — Default behaviour. Since: 2.74
  • INHERIT_STDIN = 1 — If this flag is given, the child process will inherit the parent's stdin. Otherwise, the child's stdin is redirected to /dev/null.
  • INHERIT_STDOUT = 2 — If this flag is given, the child process will inherit the parent's stdout. Otherwise, the child's stdout will not be visible, but it will be captured to allow later tests with GLib.test_trap_assert_stdout.
  • INHERIT_STDERR = 4 — If this flag is given, the child process will inherit the parent's stderr. Otherwise, the child's stderr will not be visible, but it will be captured to allow later tests with GLib.test_trap_assert_stderr.
  • INHERIT_DESCRIPTORS = 8 — If this flag is given, the child process will inherit the parent’s open file descriptors.

TestTrapFlags

Bit flags.

  • DEFAULT = 0 — Default behaviour. Since: 2.74
  • SILENCE_STDOUT = 128 — Redirect stdout of the test child to /dev/null so it cannot be observed on the console during test runs. The actual output is still captured though to allow later tests with g_test_trap_assert_stdout().
  • SILENCE_STDERR = 256 — Redirect stderr of the test child to /dev/null so it cannot be observed on the console during test runs. The actual output is still captured though to allow later tests with g_test_trap_assert_stderr().
  • INHERIT_STDIN = 512 — If this flag is given, stdin of the child process is shared with stdin of its parent process. It is redirected to /dev/null otherwise.

ThreadError

Enumeration.

  • THREAD_ERROR_AGAIN = 0 — a thread couldn't be created due to resource shortage. Try again later.

TimeType

Enumeration.

  • STANDARD = 0 — the time is in local standard time
  • DAYLIGHT = 1 — the time is in local daylight time
  • UNIVERSAL = 2 — the time is in UTC

TokenType

Enumeration.

  • EOF = 0 — the end of the file
  • LEFT_PAREN = 40 — a '(' character
  • RIGHT_PAREN = 41 — a ')' character
  • LEFT_CURLY = 123 — a '{' character
  • RIGHT_CURLY = 125 — a '}' character
  • LEFT_BRACE = 91 — a '[' character
  • RIGHT_BRACE = 93 — a ']' character
  • EQUAL_SIGN = 61 — a '=' character
  • COMMA = 44 — a ',' character
  • NONE = 256 — not a token
  • ERROR = 257 — an error occurred
  • CHAR = 258 — a character
  • BINARY = 259 — a binary integer
  • OCTAL = 260 — an octal integer
  • INT = 261 — an integer
  • HEX = 262 — a hex integer
  • FLOAT = 263 — a floating point number
  • STRING = 264 — a string
  • SYMBOL = 265 — a symbol
  • IDENTIFIER = 266 — an identifier
  • IDENTIFIER_NULL = 267 — a null identifier
  • COMMENT_SINGLE = 268 — one line comment
  • COMMENT_MULTI = 269 — multi line comment

TraverseFlags

Bit flags.

  • LEAVES = 1 — only leaf nodes should be visited. This name has been introduced in 2.6, for older version use TraverseFlags.LEAFS.
  • NON_LEAVES = 2 — only non-leaf nodes should be visited. This name has been introduced in 2.6, for older version use TraverseFlags.NON_LEAFS.
  • ALL = 3 — all nodes should be visited.
  • MASK = 3 — a mask of all traverse flags.
  • LEAFS = 1 — identical to TraverseFlags.LEAVES.
  • NON_LEAFS = 2 — identical to TraverseFlags.NON_LEAVES.

TraverseType

Enumeration.

  • IN_ORDER = 0 — visits a node's left child first, then the node itself, then its right child. This is the one to use if you want the output sorted according to the compare function.
  • PRE_ORDER = 1 — visits a node, then its children.
  • POST_ORDER = 2 — visits the node's children, then the node itself.
  • LEVEL_ORDER = 3 — is not implemented for balanced binary trees. For n-ary trees, it visits the root node first, then its children, then its grandchildren, and so on. Note that this is less efficient than the other orders.

UnicodeBreakType

Enumeration.

  • MANDATORY = 0 — Mandatory Break (BK)
  • CARRIAGE_RETURN = 1 — Carriage Return (CR)
  • LINE_FEED = 2 — Line Feed (LF)
  • COMBINING_MARK = 3 — Attached Characters and Combining Marks (CM)
  • SURROGATE = 4 — Surrogates (SG)
  • ZERO_WIDTH_SPACE = 5 — Zero Width Space (ZW)
  • INSEPARABLE = 6 — Inseparable (IN)
  • NON_BREAKING_GLUE = 7 — Non-breaking ("Glue") (GL)
  • CONTINGENT = 8 — Contingent Break Opportunity (CB)
  • SPACE = 9 — Space (SP)
  • AFTER = 10 — Break Opportunity After (BA)
  • BEFORE = 11 — Break Opportunity Before (BB)
  • BEFORE_AND_AFTER = 12 — Break Opportunity Before and After (B2)
  • HYPHEN = 13 — Hyphen (HY)
  • NON_STARTER = 14 — Nonstarter (NS)
  • OPEN_PUNCTUATION = 15 — Opening Punctuation (OP)
  • CLOSE_PUNCTUATION = 16 — Closing Punctuation (CL)
  • QUOTATION = 17 — Ambiguous Quotation (QU)
  • EXCLAMATION = 18 — Exclamation/Interrogation (EX)
  • IDEOGRAPHIC = 19 — Ideographic (ID)
  • NUMERIC = 20 — Numeric (NU)
  • INFIX_SEPARATOR = 21 — Infix Separator (Numeric) (IS)
  • SYMBOL = 22 — Symbols Allowing Break After (SY)
  • ALPHABETIC = 23 — Ordinary Alphabetic and Symbol Characters (AL)
  • PREFIX = 24 — Prefix (Numeric) (PR)
  • POSTFIX = 25 — Postfix (Numeric) (PO)
  • COMPLEX_CONTEXT = 26 — Complex Content Dependent (South East Asian) (SA)
  • AMBIGUOUS = 27 — Ambiguous (Alphabetic or Ideographic) (AI)
  • UNKNOWN = 28 — Unknown (XX)
  • NEXT_LINE = 29 — Next Line (NL)
  • WORD_JOINER = 30 — Word Joiner (WJ)
  • HANGUL_L_JAMO = 31 — Hangul L Jamo (JL)
  • HANGUL_V_JAMO = 32 — Hangul V Jamo (JV)
  • HANGUL_T_JAMO = 33 — Hangul T Jamo (JT)
  • HANGUL_LV_SYLLABLE = 34 — Hangul LV Syllable (H2)
  • HANGUL_LVT_SYLLABLE = 35 — Hangul LVT Syllable (H3)
  • CLOSE_PARANTHESIS = 36 — Closing Parenthesis (CP). Since 2.28. Deprecated: 2.70: Use UnicodeBreakType.CLOSE_PARENTHESIS instead.
  • CLOSE_PARENTHESIS = 36 — Closing Parenthesis (CP). Since 2.70
  • CONDITIONAL_JAPANESE_STARTER = 37 — Conditional Japanese Starter (CJ). Since: 2.32
  • HEBREW_LETTER = 38 — Hebrew Letter (HL). Since: 2.32
  • REGIONAL_INDICATOR = 39 — Regional Indicator (RI). Since: 2.36
  • EMOJI_BASE = 40 — Emoji Base (EB). Since: 2.50
  • EMOJI_MODIFIER = 41 — Emoji Modifier (EM). Since: 2.50
  • ZERO_WIDTH_JOINER = 42 — Zero Width Joiner (ZWJ). Since: 2.50
  • AKSARA = 43 — Aksara (AK). Since: 2.80
  • AKSARA_PRE_BASE = 44 — Aksara Pre-Base (AP). Since: 2.80
  • AKSARA_START = 45 — Aksara Start (AS). Since: 2.80
  • VIRAMA_FINAL = 46 — Virama Final (VF). Since: 2.80
  • VIRAMA = 47 — Virama (VI). Since: 2.80
  • UNAMBIGUOUS_HYPHEN = 48 — Unambiguous Hyphen (HH). Since: 2.88

UnicodeScript

Enumeration.

  • INVALID_CODE = -1 — a value never returned from unichar_get_script
  • COMMON = 0 — a character used by multiple different scripts
  • INHERITED = 1 — a mark glyph that takes its script from the base glyph to which it is attached
  • ARABIC = 2 — Arabic
  • ARMENIAN = 3 — Armenian
  • BENGALI = 4 — Bengali
  • BOPOMOFO = 5 — Bopomofo
  • CHEROKEE = 6 — Cherokee
  • COPTIC = 7 — Coptic
  • CYRILLIC = 8 — Cyrillic
  • DESERET = 9 — Deseret
  • DEVANAGARI = 10 — Devanagari
  • ETHIOPIC = 11 — Ethiopic
  • GEORGIAN = 12 — Georgian
  • GOTHIC = 13 — Gothic
  • GREEK = 14 — Greek
  • GUJARATI = 15 — Gujarati
  • GURMUKHI = 16 — Gurmukhi
  • HAN = 17 — Han
  • HANGUL = 18 — Hangul
  • HEBREW = 19 — Hebrew
  • HIRAGANA = 20 — Hiragana
  • KANNADA = 21 — Kannada
  • KATAKANA = 22 — Katakana
  • KHMER = 23 — Khmer
  • LAO = 24 — Lao
  • LATIN = 25 — Latin
  • MALAYALAM = 26 — Malayalam
  • MONGOLIAN = 27 — Mongolian
  • MYANMAR = 28 — Myanmar
  • OGHAM = 29 — Ogham
  • OLD_ITALIC = 30 — Old Italic
  • ORIYA = 31 — Oriya
  • RUNIC = 32 — Runic
  • SINHALA = 33 — Sinhala
  • SYRIAC = 34 — Syriac
  • TAMIL = 35 — Tamil
  • TELUGU = 36 — Telugu
  • THAANA = 37 — Thaana
  • THAI = 38 — Thai
  • TIBETAN = 39 — Tibetan
  • CANADIAN_ABORIGINAL = 40 — Canadian Aboriginal
  • YI = 41 — Yi
  • TAGALOG = 42 — Tagalog
  • HANUNOO = 43 — Hanunoo
  • BUHID = 44 — Buhid
  • TAGBANWA = 45 — Tagbanwa
  • BRAILLE = 46 — Braille
  • CYPRIOT = 47 — Cypriot
  • LIMBU = 48 — Limbu
  • OSMANYA = 49 — Osmanya
  • SHAVIAN = 50 — Shavian
  • LINEAR_B = 51 — Linear B
  • TAI_LE = 52 — Tai Le
  • UGARITIC = 53 — Ugaritic
  • NEW_TAI_LUE = 54 — New Tai Lue
  • BUGINESE = 55 — Buginese
  • GLAGOLITIC = 56 — Glagolitic
  • TIFINAGH = 57 — Tifinagh
  • SYLOTI_NAGRI = 58 — Syloti Nagri
  • OLD_PERSIAN = 59 — Old Persian
  • KHAROSHTHI = 60 — Kharoshthi
  • UNKNOWN = 61 — an unassigned code point
  • BALINESE = 62 — Balinese
  • CUNEIFORM = 63 — Cuneiform
  • PHOENICIAN = 64 — Phoenician
  • PHAGS_PA = 65 — Phags-pa
  • NKO = 66 — N'Ko
  • KAYAH_LI = 67 — Kayah Li. Since 2.16.3
  • LEPCHA = 68 — Lepcha. Since 2.16.3
  • REJANG = 69 — Rejang. Since 2.16.3
  • SUNDANESE = 70 — Sundanese. Since 2.16.3
  • SAURASHTRA = 71 — Saurashtra. Since 2.16.3
  • CHAM = 72 — Cham. Since 2.16.3
  • OL_CHIKI = 73 — Ol Chiki. Since 2.16.3
  • VAI = 74 — Vai. Since 2.16.3
  • CARIAN = 75 — Carian. Since 2.16.3
  • LYCIAN = 76 — Lycian. Since 2.16.3
  • LYDIAN = 77 — Lydian. Since 2.16.3
  • AVESTAN = 78 — Avestan. Since 2.26
  • BAMUM = 79 — Bamum. Since 2.26
  • EGYPTIAN_HIEROGLYPHS = 80 — Egyptian Hieroglpyhs. Since 2.26
  • IMPERIAL_ARAMAIC = 81 — Imperial Aramaic. Since 2.26
  • INSCRIPTIONAL_PAHLAVI = 82 — Inscriptional Pahlavi. Since 2.26
  • INSCRIPTIONAL_PARTHIAN = 83 — Inscriptional Parthian. Since 2.26
  • JAVANESE = 84 — Javanese. Since 2.26
  • KAITHI = 85 — Kaithi. Since 2.26
  • LISU = 86 — Lisu. Since 2.26
  • MEETEI_MAYEK = 87 — Meetei Mayek. Since 2.26
  • OLD_SOUTH_ARABIAN = 88 — Old South Arabian. Since 2.26
  • OLD_TURKIC = 89 — Old Turkic. Since 2.28
  • SAMARITAN = 90 — Samaritan. Since 2.26
  • TAI_THAM = 91 — Tai Tham. Since 2.26
  • TAI_VIET = 92 — Tai Viet. Since 2.26
  • BATAK = 93 — Batak. Since 2.28
  • BRAHMI = 94 — Brahmi. Since 2.28
  • MANDAIC = 95 — Mandaic. Since 2.28
  • CHAKMA = 96 — Chakma. Since: 2.32
  • MEROITIC_CURSIVE = 97 — Meroitic Cursive. Since: 2.32
  • MEROITIC_HIEROGLYPHS = 98 — Meroitic Hieroglyphs. Since: 2.32
  • MIAO = 99 — Miao. Since: 2.32
  • SHARADA = 100 — Sharada. Since: 2.32
  • SORA_SOMPENG = 101 — Sora Sompeng. Since: 2.32
  • TAKRI = 102 — Takri. Since: 2.32
  • BASSA_VAH = 103 — Bassa. Since: 2.42
  • CAUCASIAN_ALBANIAN = 104 — Caucasian Albanian. Since: 2.42
  • DUPLOYAN = 105 — Duployan. Since: 2.42
  • ELBASAN = 106 — Elbasan. Since: 2.42
  • GRANTHA = 107 — Grantha. Since: 2.42
  • KHOJKI = 108 — Kjohki. Since: 2.42
  • KHUDAWADI = 109 — Khudawadi, Sindhi. Since: 2.42
  • LINEAR_A = 110 — Linear A. Since: 2.42
  • MAHAJANI = 111 — Mahajani. Since: 2.42
  • MANICHAEAN = 112 — Manichaean. Since: 2.42
  • MENDE_KIKAKUI = 113 — Mende Kikakui. Since: 2.42
  • MODI = 114 — Modi. Since: 2.42
  • MRO = 115 — Mro. Since: 2.42
  • NABATAEAN = 116 — Nabataean. Since: 2.42
  • OLD_NORTH_ARABIAN = 117 — Old North Arabian. Since: 2.42
  • OLD_PERMIC = 118 — Old Permic. Since: 2.42
  • PAHAWH_HMONG = 119 — Pahawh Hmong. Since: 2.42
  • PALMYRENE = 120 — Palmyrene. Since: 2.42
  • PAU_CIN_HAU = 121 — Pau Cin Hau. Since: 2.42
  • PSALTER_PAHLAVI = 122 — Psalter Pahlavi. Since: 2.42
  • SIDDHAM = 123 — Siddham. Since: 2.42
  • TIRHUTA = 124 — Tirhuta. Since: 2.42
  • WARANG_CITI = 125 — Warang Citi. Since: 2.42
  • AHOM = 126 — Ahom. Since: 2.48
  • ANATOLIAN_HIEROGLYPHS = 127 — Anatolian Hieroglyphs. Since: 2.48
  • HATRAN = 128 — Hatran. Since: 2.48
  • MULTANI = 129 — Multani. Since: 2.48
  • OLD_HUNGARIAN = 130 — Old Hungarian. Since: 2.48
  • SIGNWRITING = 131 — Signwriting. Since: 2.48
  • ADLAM = 132 — Adlam. Since: 2.50
  • BHAIKSUKI = 133 — Bhaiksuki. Since: 2.50
  • MARCHEN = 134 — Marchen. Since: 2.50
  • NEWA = 135 — Newa. Since: 2.50
  • OSAGE = 136 — Osage. Since: 2.50
  • TANGUT = 137 — Tangut. Since: 2.50
  • MASARAM_GONDI = 138 — Masaram Gondi. Since: 2.54
  • NUSHU = 139 — Nushu. Since: 2.54
  • SOYOMBO = 140 — Soyombo. Since: 2.54
  • ZANABAZAR_SQUARE = 141 — Zanabazar Square. Since: 2.54
  • DOGRA = 142 — Dogra. Since: 2.58
  • GUNJALA_GONDI = 143 — Gunjala Gondi. Since: 2.58
  • HANIFI_ROHINGYA = 144 — Hanifi Rohingya. Since: 2.58
  • MAKASAR = 145 — Makasar. Since: 2.58
  • MEDEFAIDRIN = 146 — Medefaidrin. Since: 2.58
  • OLD_SOGDIAN = 147 — Old Sogdian. Since: 2.58
  • SOGDIAN = 148 — Sogdian. Since: 2.58
  • ELYMAIC = 149 — Elym. Since: 2.62
  • NANDINAGARI = 150 — Nand. Since: 2.62
  • NYIAKENG_PUACHUE_HMONG = 151 — Rohg. Since: 2.62
  • WANCHO = 152 — Wcho. Since: 2.62
  • CHORASMIAN = 153 — Chorasmian. Since: 2.66
  • DIVES_AKURU = 154 — Dives Akuru. Since: 2.66
  • KHITAN_SMALL_SCRIPT = 155 — Khitan small script. Since: 2.66
  • YEZIDI = 156 — Yezidi. Since: 2.66
  • CYPRO_MINOAN = 157 — Cypro-Minoan. Since: 2.72
  • OLD_UYGHUR = 158 — Old Uyghur. Since: 2.72
  • TANGSA = 159 — Tangsa. Since: 2.72
  • TOTO = 160 — Toto. Since: 2.72
  • VITHKUQI = 161 — Vithkuqi. Since: 2.72
  • MATH = 162 — Mathematical notation. Since: 2.72
  • KAWI = 163 — Kawi. Since 2.74
  • NAG_MUNDARI = 164 — Nag Mundari. Since 2.74
  • TODHRI = 165 — Todhri. Since: 2.84
  • GARAY = 166 — Garay. Since: 2.84
  • TULU_TIGALARI = 167 — Tulu-Tigalari. Since: 2.84
  • SUNUWAR = 168 — Sunuwar. Since: 2.84
  • GURUNG_KHEMA = 169 — Gurung Khema. Since: 2.84
  • KIRAT_RAI = 170 — Kirat Rai. Since: 2.84
  • OL_ONAL = 171 — Ol Onal. Since: 2.84
  • SIDETIC = 172 — Sidetic. Since: 2.88
  • TOLONG_SIKI = 173 — Tolong Siki. Since: 2.88
  • TAI_YO = 174 — Tai Yo. Since: 2.88
  • BERIA_ERFE = 175 — Beria Erfe. Since: 2.88

UnicodeType

Enumeration.

  • CONTROL = 0 — General category "Other, Control" (Cc)
  • FORMAT = 1 — General category "Other, Format" (Cf)
  • UNASSIGNED = 2 — General category "Other, Not Assigned" (Cn)
  • PRIVATE_USE = 3 — General category "Other, Private Use" (Co)
  • SURROGATE = 4 — General category "Other, Surrogate" (Cs)
  • LOWERCASE_LETTER = 5 — General category "Letter, Lowercase" (Ll)
  • MODIFIER_LETTER = 6 — General category "Letter, Modifier" (Lm)
  • OTHER_LETTER = 7 — General category "Letter, Other" (Lo)
  • TITLECASE_LETTER = 8 — General category "Letter, Titlecase" (Lt)
  • UPPERCASE_LETTER = 9 — General category "Letter, Uppercase" (Lu)
  • SPACING_MARK = 10 — General category "Mark, Spacing" (Mc)
  • ENCLOSING_MARK = 11 — General category "Mark, Enclosing" (Me)
  • NON_SPACING_MARK = 12 — General category "Mark, Nonspacing" (Mn)
  • DECIMAL_NUMBER = 13 — General category "Number, Decimal Digit" (Nd)
  • LETTER_NUMBER = 14 — General category "Number, Letter" (Nl)
  • OTHER_NUMBER = 15 — General category "Number, Other" (No)
  • CONNECT_PUNCTUATION = 16 — General category "Punctuation, Connector" (Pc)
  • DASH_PUNCTUATION = 17 — General category "Punctuation, Dash" (Pd)
  • CLOSE_PUNCTUATION = 18 — General category "Punctuation, Close" (Pe)
  • FINAL_PUNCTUATION = 19 — General category "Punctuation, Final quote" (Pf)
  • INITIAL_PUNCTUATION = 20 — General category "Punctuation, Initial quote" (Pi)
  • OTHER_PUNCTUATION = 21 — General category "Punctuation, Other" (Po)
  • OPEN_PUNCTUATION = 22 — General category "Punctuation, Open" (Ps)
  • CURRENCY_SYMBOL = 23 — General category "Symbol, Currency" (Sc)
  • MODIFIER_SYMBOL = 24 — General category "Symbol, Modifier" (Sk)
  • MATH_SYMBOL = 25 — General category "Symbol, Math" (Sm)
  • OTHER_SYMBOL = 26 — General category "Symbol, Other" (So)
  • LINE_SEPARATOR = 27 — General category "Separator, Line" (Zl)
  • PARAGRAPH_SEPARATOR = 28 — General category "Separator, Paragraph" (Zp)
  • SPACE_SEPARATOR = 29 — General category "Separator, Space" (Zs)

UriError

Enumeration.

  • FAILED = 0 — Generic error if no more specific error is available. See the error message for details.
  • BAD_SCHEME = 1 — The scheme of a URI could not be parsed.
  • BAD_USER = 2 — The user/userinfo of a URI could not be parsed.
  • BAD_PASSWORD = 3 — The password of a URI could not be parsed.
  • BAD_AUTH_PARAMS = 4 — The authentication parameters of a URI could not be parsed.
  • BAD_HOST = 5 — The host of a URI could not be parsed.
  • BAD_PORT = 6 — The port of a URI could not be parsed.
  • BAD_PATH = 7 — The path of a URI could not be parsed.
  • BAD_QUERY = 8 — The query of a URI could not be parsed.
  • BAD_FRAGMENT = 9 — The fragment of a URI could not be parsed.

UriFlags

Bit flags.

  • NONE = 0 — No flags set.
  • PARSE_RELAXED = 1 — Parse the URI more relaxedly than the RFC 3986 grammar specifies, fixing up or ignoring common mistakes in URIs coming from external sources. This is also needed for some obscure URI schemes where ; separates the host from the path. Don’t use this flag unless you need to.
  • HAS_PASSWORD = 2 — The userinfo field may contain a password, which will be separated from the username by :.
  • HAS_AUTH_PARAMS = 4 — The userinfo may contain additional authentication-related parameters, which will be separated from the username and/or password by ;.
  • ENCODED = 8 — When parsing a URI, this indicates that %-encoded characters in the userinfo, path, query, and fragment fields should not be decoded. (And likewise the host field if UriFlags.NON_DNS is also set.) When building a URI, it indicates that you have already %-encoded the components, and so Uri should not do any encoding itself.
  • NON_DNS = 16 — The host component should not be assumed to be a DNS hostname or IP address (for example, for smb URIs with NetBIOS hostnames).
  • ENCODED_QUERY = 32 — Same as UriFlags.ENCODED, for the query field only.
  • ENCODED_PATH = 64 — Same as UriFlags.ENCODED, for the path only.
  • ENCODED_FRAGMENT = 128 — Same as UriFlags.ENCODED, for the fragment only.
  • SCHEME_NORMALIZE = 256 — A scheme-based normalization will be applied. For example, when parsing an HTTP URI changing omitted path to / and omitted port to 80; and when building a URI, changing empty path to / and default port 80). This only supports a subset of known schemes. (Since: 2.68)

UriHideFlags

Bit flags.

  • NONE = 0 — No flags set.
  • USERINFO = 1 — Hide the userinfo.
  • PASSWORD = 2 — Hide the password.
  • AUTH_PARAMS = 4 — Hide the auth_params.
  • QUERY = 8 — Hide the query.
  • FRAGMENT = 16 — Hide the fragment.

UriParamsFlags

Bit flags.

  • NONE = 0 — No flags set.
  • CASE_INSENSITIVE = 1 — Parameter names are case insensitive.
  • WWW_FORM = 2 — Replace + with space character. Only useful for URLs on the web, using the https or http schemas.
  • PARSE_RELAXED = 4 — See UriFlags.PARSE_RELAXED.

UserDirectory

Enumeration.

  • DIRECTORY_DESKTOP = 0 — the user's Desktop directory
  • DIRECTORY_DOCUMENTS = 1 — the user's Documents directory
  • DIRECTORY_DOWNLOAD = 2 — the user's Downloads directory
  • DIRECTORY_MUSIC = 3 — the user's Music directory
  • DIRECTORY_PICTURES = 4 — the user's Pictures directory
  • DIRECTORY_PUBLIC_SHARE = 5 — the user's shared directory
  • DIRECTORY_TEMPLATES = 6 — the user's Templates directory
  • DIRECTORY_VIDEOS = 7 — the user's Movies directory
  • N_DIRECTORIES = 8 — the number of enum values

VariantClass

Enumeration.

  • BOOLEAN = 98 — The Variant is a boolean.
  • BYTE = 121 — The Variant is a byte.
  • INT16 = 110 — The Variant is a signed 16 bit integer.
  • UINT16 = 113 — The Variant is an unsigned 16 bit integer.
  • INT32 = 105 — The Variant is a signed 32 bit integer.
  • UINT32 = 117 — The Variant is an unsigned 32 bit integer.
  • INT64 = 120 — The Variant is a signed 64 bit integer.
  • UINT64 = 116 — The Variant is an unsigned 64 bit integer.
  • HANDLE = 104 — The Variant is a file handle index.
  • DOUBLE = 100 — The Variant is a double precision floating point value.
  • STRING = 115 — The Variant is a normal string.
  • OBJECT_PATH = 111 — The Variant is a D-Bus object path string.
  • SIGNATURE = 103 — The Variant is a D-Bus signature string.
  • VARIANT = 118 — The Variant is a variant.
  • MAYBE = 109 — The Variant is a maybe-typed value.
  • ARRAY = 97 — The Variant is an array.
  • TUPLE = 40 — The Variant is a tuple.
  • DICT_ENTRY = 123 — The Variant is a dictionary entry.

VariantParseError

Enumeration.

  • FAILED = 0 — generic error (unused)
  • BASIC_TYPE_EXPECTED = 1 — a non-basic VariantType was given where a basic type was expected
  • CANNOT_INFER_TYPE = 2 — cannot infer the VariantType
  • DEFINITE_TYPE_EXPECTED = 3 — an indefinite VariantType was given where a definite type was expected
  • INPUT_NOT_AT_END = 4 — extra data after parsing finished
  • INVALID_CHARACTER = 5 — invalid character in number or unicode escape
  • INVALID_FORMAT_STRING = 6 — not a valid Variant format string
  • INVALID_OBJECT_PATH = 7 — not a valid object path
  • INVALID_SIGNATURE = 8 — not a valid type signature
  • INVALID_TYPE_STRING = 9 — not a valid Variant type string
  • NO_COMMON_TYPE = 10 — could not find a common type for array entries
  • NUMBER_OUT_OF_RANGE = 11 — the numerical value is out of range of the given type
  • NUMBER_TOO_BIG = 12 — the numerical value is out of range for any type
  • TYPE_ERROR = 13 — cannot parse as variant of the specified type
  • UNEXPECTED_TOKEN = 14 — an unexpected token was encountered
  • UNKNOWN_KEYWORD = 15 — an unknown keyword was encountered
  • UNTERMINATED_STRING_CONSTANT = 16 — unterminated string constant
  • VALUE_EXPECTED = 17 — no value given
  • RECURSION = 18 — variant was too deeply nested; Variant is only guaranteed to handle nesting up to 64 levels (Since: 2.64)

Constants

ALLOCATOR_LIST

ALLOCATOR_LIST: int

ALLOCATOR_NODE

ALLOCATOR_NODE: int

ALLOCATOR_SLIST

ALLOCATOR_SLIST: int

ALLOC_AND_FREE

ALLOC_AND_FREE: int

ALLOC_ONLY

ALLOC_ONLY: int

ANALYZER_ANALYZING

ANALYZER_ANALYZING: int

ASCII_DTOSTR_BUF_SIZE

ASCII_DTOSTR_BUF_SIZE: int

A good size for a buffer to be passed into ascii_dtostr. It is guaranteed to be enough for all output of that function on systems with 64bit IEEE-compatible doubles.

The typical usage would be something like:

char buf[G_ASCII_DTOSTR_BUF_SIZE];

fprintf (out, "value=%s\n", g_ascii_dtostr (buf, sizeof (buf), value));

ATOMIC_REF_COUNT_INIT

ATOMIC_REF_COUNT_INIT: int

Evaluates to the initial reference count for gatomicrefcount.

This macro is useful for initializing gatomicrefcount fields inside structures, for instance:

typedef struct {
  gatomicrefcount ref_count;
  char *name;
  char *address;
} Person;

static const Person default_person = {
  .ref_count = G_ATOMIC_REF_COUNT_INIT,
  .name = "Default name",
  .address = "Default address",
};

BIG_ENDIAN

BIG_ENDIAN: int

Specifies one of the possible types of byte order. See G_BYTE_ORDER.

CSET_A_2_Z

CSET_A_2_Z: str

The set of uppercase ASCII alphabet characters. Used for specifying valid identifier characters in ScannerConfig.

CSET_DIGITS

CSET_DIGITS: str

The set of ASCII digits. Used for specifying valid identifier characters in ScannerConfig.

CSET_a_2_z

CSET_a_2_z: str

The set of lowercase ASCII alphabet characters. Used for specifying valid identifier characters in ScannerConfig.

C_STD_VERSION

C_STD_VERSION: int

The C standard version the code is compiling against, it's normally defined with the same value of __STDC_VERSION__ for C standard compatible compilers, while it uses the lowest standard version in pure MSVC, given that in such compiler the definition depends on a compilation flag.

This is granted to be undefined when compiling with a C++ compiler.

See also: G_C_STD_CHECK_VERSION and G_CXX_STD_VERSION

DATALIST_FLAGS_MASK

DATALIST_FLAGS_MASK: int

A bitmask that restricts the possible flags passed to datalist_set_flags. Passing a flags value where flags & ~G_DATALIST_FLAGS_MASK != 0 is an error.

DATE_BAD_DAY

DATE_BAD_DAY: int

Represents an invalid GDateDay.

DATE_BAD_JULIAN

DATE_BAD_JULIAN: int

Represents an invalid Julian day number.

DATE_BAD_YEAR

DATE_BAD_YEAR: int

Represents an invalid year.

DIR_SEPARATOR

DIR_SEPARATOR: int

The directory separator character.

This is '/' on UNIX machines and '\' under Windows.

DIR_SEPARATOR_S

DIR_SEPARATOR_S: str

The directory separator as a string.

This is "/" on UNIX machines and "\" under Windows.

E

E: float

The base of natural logarithms.

GINT16_FORMAT

GINT16_FORMAT: str

GINT16_MODIFIER

GINT16_MODIFIER: str

GINT32_FORMAT

GINT32_FORMAT: str

GINT32_MODIFIER

GINT32_MODIFIER: str

GINT64_FORMAT

GINT64_FORMAT: str

GINT64_MODIFIER

GINT64_MODIFIER: str

GINTPTR_FORMAT

GINTPTR_FORMAT: str

GINTPTR_MODIFIER

GINTPTR_MODIFIER: str

GNUC_FUNCTION

GNUC_FUNCTION: str

Expands to "" on all modern compilers, and to FUNCTION on gcc version 2.x. Don't use it.

GNUC_PRETTY_FUNCTION

GNUC_PRETTY_FUNCTION: str

Expands to "" on all modern compilers, and to PRETTY_FUNCTION on gcc version 2.x. Don't use it.

GSIZE_FORMAT

GSIZE_FORMAT: str

GSIZE_MODIFIER

GSIZE_MODIFIER: str

GSSIZE_FORMAT

GSSIZE_FORMAT: str

GSSIZE_MODIFIER

GSSIZE_MODIFIER: str

GUINT16_FORMAT

GUINT16_FORMAT: str

GUINT32_FORMAT

GUINT32_FORMAT: str

GUINT64_FORMAT

GUINT64_FORMAT: str

GUINTPTR_FORMAT

GUINTPTR_FORMAT: str

HAVE_GINT64

HAVE_GINT64: int

HAVE_GNUC_VARARGS

HAVE_GNUC_VARARGS: int

HAVE_GNUC_VISIBILITY

HAVE_GNUC_VISIBILITY: int

Defined to 1 if gcc-style visibility handling is supported.

HAVE_GROWING_STACK

HAVE_GROWING_STACK: int

HAVE_ISO_VARARGS

HAVE_ISO_VARARGS: int

HOOK_FLAG_USER_SHIFT

HOOK_FLAG_USER_SHIFT: int

The position of the first bit which is not reserved for internal use be the Hook implementation, i.e. 1 << G_HOOK_FLAG_USER_SHIFT is the first bit which can be used for application-defined flags.

IEEE754_DOUBLE_BIAS

IEEE754_DOUBLE_BIAS: int

The bias by which exponents in double-precision floats are offset.

IEEE754_FLOAT_BIAS

IEEE754_FLOAT_BIAS: int

The bias by which exponents in single-precision floats are offset.

KEY_FILE_DESKTOP_GROUP

KEY_FILE_DESKTOP_GROUP: str

The name of the main group of a desktop entry file, as defined in the Desktop Entry Specification.

Consult the specification for more details about the meanings of the keys below.

KEY_FILE_DESKTOP_KEY_ACTIONS

KEY_FILE_DESKTOP_KEY_ACTIONS: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a string list giving the available application actions.

KEY_FILE_DESKTOP_KEY_CATEGORIES

KEY_FILE_DESKTOP_KEY_CATEGORIES: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the categories in which the desktop entry should be shown in a menu.

KEY_FILE_DESKTOP_KEY_COMMENT

KEY_FILE_DESKTOP_KEY_COMMENT: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the tooltip for the desktop entry.

KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE

KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean set to true if the application is D-Bus activatable.

KEY_FILE_DESKTOP_KEY_EXEC

KEY_FILE_DESKTOP_KEY_EXEC: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the command line to execute.

It is only valid for desktop entries with the Application type.

KEY_FILE_DESKTOP_KEY_GENERIC_NAME

KEY_FILE_DESKTOP_KEY_GENERIC_NAME: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the generic name of the desktop entry.

KEY_FILE_DESKTOP_KEY_HIDDEN

KEY_FILE_DESKTOP_KEY_HIDDEN: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry has been deleted by the user.

KEY_FILE_DESKTOP_KEY_ICON

KEY_FILE_DESKTOP_KEY_ICON: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the name of the icon to be displayed for the desktop entry.

KEY_FILE_DESKTOP_KEY_MIME_TYPE

KEY_FILE_DESKTOP_KEY_MIME_TYPE: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a list of strings giving the MIME types supported by this desktop entry.

KEY_FILE_DESKTOP_KEY_NAME

KEY_FILE_DESKTOP_KEY_NAME: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a localized string giving the specific name of the desktop entry.

KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN

KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should not display the desktop entry.

KEY_FILE_DESKTOP_KEY_NO_DISPLAY

KEY_FILE_DESKTOP_KEY_NO_DISPLAY: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the desktop entry should be shown in menus.

KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN

KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a list of strings identifying the environments that should display the desktop entry.

KEY_FILE_DESKTOP_KEY_PATH

KEY_FILE_DESKTOP_KEY_PATH: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a string containing the working directory to run the program in.

It is only valid for desktop entries with the Application type.

KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY

KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the application supports the Startup Notification Protocol Specification.

KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS

KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is string identifying the WM class or name hint of a window that the application will create, which can be used to emulate Startup Notification with older applications.

KEY_FILE_DESKTOP_KEY_TERMINAL

KEY_FILE_DESKTOP_KEY_TERMINAL: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a boolean stating whether the program should be run in a terminal window.

It is only valid for desktop entries with the Application type.

KEY_FILE_DESKTOP_KEY_TRY_EXEC

KEY_FILE_DESKTOP_KEY_TRY_EXEC: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the file name of a binary on disk used to determine if the program is actually installed.

It is only valid for desktop entries with the Application type.

KEY_FILE_DESKTOP_KEY_TYPE

KEY_FILE_DESKTOP_KEY_TYPE: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the type of the desktop entry.

Usually KEY_FILE_DESKTOP_TYPE_APPLICATION, KEY_FILE_DESKTOP_TYPE_LINK, or KEY_FILE_DESKTOP_TYPE_DIRECTORY.

KEY_FILE_DESKTOP_KEY_URL

KEY_FILE_DESKTOP_KEY_URL: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the URL to access.

It is only valid for desktop entries with the Link type.

KEY_FILE_DESKTOP_KEY_VERSION

KEY_FILE_DESKTOP_KEY_VERSION: str

A key under KEY_FILE_DESKTOP_GROUP, whose value is a string giving the version of the Desktop Entry Specification used for the desktop entry file.

KEY_FILE_DESKTOP_TYPE_APPLICATION

KEY_FILE_DESKTOP_TYPE_APPLICATION: str

The value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing applications.

KEY_FILE_DESKTOP_TYPE_DIRECTORY

KEY_FILE_DESKTOP_TYPE_DIRECTORY: str

The value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing directories.

KEY_FILE_DESKTOP_TYPE_LINK: str

The value of the KEY_FILE_DESKTOP_KEY_TYPE, key for desktop entries representing links to documents.

LITTLE_ENDIAN

LITTLE_ENDIAN: int

Specifies one of the possible types of byte order. See G_BYTE_ORDER.

LN10

LN10: float

The natural logarithm of 10.

LN2

LN2: float

The natural logarithm of 2.

LOG_2_BASE_10

LOG_2_BASE_10: float

Multiplying the base 2 exponent by this number yields the base 10 exponent.

LOG_DOMAIN

LOG_DOMAIN: int

Defines the log domain. See Log Domains.

Libraries should define this so that any messages which they log can be differentiated from messages from other libraries and application code. But be careful not to define it in any public header files.

Log domains must be unique, and it is recommended that they are the application or library name, optionally followed by a hyphen and a sub-domain name. For example, bloatpad or bloatpad-io.

If undefined, it defaults to the default None (or "") log domain; this is not advisable, as it cannot be filtered against using the G_MESSAGES_DEBUG environment variable.

For example, GTK uses this in its Makefile.am:

AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"

Applications can choose to leave it as the default None (or "") domain. However, defining the domain offers the same advantages as above.

LOG_FATAL_MASK

LOG_FATAL_MASK: int

GLib log levels that are considered fatal by default.

This is not used if structured logging is enabled; see Using Structured Logging.

LOG_LEVEL_USER_SHIFT

LOG_LEVEL_USER_SHIFT: int

Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib. Higher bits can be used for user-defined log levels.

MAJOR_VERSION

MAJOR_VERSION: int

The major version number of the GLib library.

Like #glib_major_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

MAXINT16

MAXINT16: int

MAXINT32

MAXINT32: int

MAXINT64

MAXINT64: int

MAXINT8

MAXINT8: int

MAXUINT16

MAXUINT16: int

MAXUINT32

MAXUINT32: int

MAXUINT64

MAXUINT64: int

MAXUINT8

MAXUINT8: int

MICRO_VERSION

MICRO_VERSION: int

The micro version number of the GLib library.

Like #gtk_micro_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

MININT16

MININT16: int

The minimum value which can be held in a #gint16.

MININT32

MININT32: int

The minimum value which can be held in a #gint32.

MININT64

MININT64: int

The minimum value which can be held in a #gint64.

MININT8

MININT8: int

The minimum value which can be held in a #gint8.

MINOR_VERSION

MINOR_VERSION: int

The minor version number of the GLib library.

Like #gtk_minor_version, but from the headers used at application compile time, rather than from the library linked against at application run time.

MODULE_SUFFIX

MODULE_SUFFIX: str

NSEC_PER_SEC

NSEC_PER_SEC: int

Number of nanoseconds in one second (1 billion). This macro is provided for code readability.

OPTION_REMAINING

OPTION_REMAINING: str

If a long option in the main group has this name, it is not treated as a regular option. Instead it collects all non-option arguments which would otherwise be left in argv. The option must be of type OptionArg.CALLBACK, OptionArg.STRING_ARRAY or OptionArg.FILENAME_ARRAY.

Using OPTION_REMAINING instead of simply scanning argv for leftover arguments has the advantage that GOption takes care of necessary encoding conversions for strings or filenames.

PDP_ENDIAN

PDP_ENDIAN: int

Specifies one of the possible types of byte order (currently unused). See G_BYTE_ORDER.

PI

PI: float

The value of pi (ratio of circle's circumference to its diameter).

PID_FORMAT

PID_FORMAT: str

A format specifier that can be used in printf()-style format strings when printing a GPid.

PI_2

PI_2: float

Pi divided by 2.

PI_4

PI_4: float

Pi divided by 4.

POLLFD_FORMAT

POLLFD_FORMAT: str

A format specifier that can be used in printf()-style format strings when printing the fd member of a PollFD.

PRIORITY_DEFAULT

PRIORITY_DEFAULT: int

Use this for default priority event sources.

In GLib this priority is used when adding timeout functions with timeout_add. In GDK this priority is used for events from the X server.

PRIORITY_DEFAULT_IDLE

PRIORITY_DEFAULT_IDLE: int

Use this for default priority idle functions.

In GLib this priority is used when adding idle functions with idle_add.

PRIORITY_HIGH

PRIORITY_HIGH: int

Use this for high priority event sources.

It is not used within GLib or GTK.

PRIORITY_HIGH_IDLE

PRIORITY_HIGH_IDLE: int

Use this for high priority idle functions.

GTK uses PRIORITY_HIGH_IDLE + 10 for resizing operations, and PRIORITY_HIGH_IDLE + 20 for redrawing operations. (This is done to ensure that any pending resizes are processed before any pending redraws, so that widgets are not redrawn twice unnecessarily.)

PRIORITY_LOW

PRIORITY_LOW: int

Use this for very low priority background tasks.

It is not used within GLib or GTK.

REF_COUNT_INIT

REF_COUNT_INIT: int

Evaluates to the initial reference count for grefcount.

This macro is useful for initializing grefcount fields inside structures, for instance:

typedef struct {
  grefcount ref_count;
  char *name;
  char *address;
} Person;

static const Person default_person = {
  .ref_count = G_REF_COUNT_INIT,
  .name = "Default name",
  .address = "Default address",
};

SEARCHPATH_SEPARATOR

SEARCHPATH_SEPARATOR: int

The search path separator character. This is ':' on UNIX machines and ';' under Windows.

SEARCHPATH_SEPARATOR_S

SEARCHPATH_SEPARATOR_S: str

The search path separator as a string. This is ":" on UNIX machines and ";" under Windows.

SIZEOF_LONG

SIZEOF_LONG: int

SIZEOF_SIZE_T

SIZEOF_SIZE_T: int

SIZEOF_SSIZE_T

SIZEOF_SSIZE_T: int

SIZEOF_VOID_P

SIZEOF_VOID_P: int

SOURCE_CONTINUE

SOURCE_CONTINUE: bool

Use this macro as the return value of a SourceFunc to leave the Source in the main loop.

SOURCE_REMOVE

SOURCE_REMOVE: bool

Use this macro as the return value of a SourceFunc to remove the Source from the main loop.

SQRT2

SQRT2: float

The square root of two.

STR_DELIMITERS

STR_DELIMITERS: str

The standard delimiters, used in strdelimit.

SYSDEF_AF_INET

SYSDEF_AF_INET: int

SYSDEF_AF_INET6

SYSDEF_AF_INET6: int

SYSDEF_AF_UNIX

SYSDEF_AF_UNIX: int

SYSDEF_MSG_DONTROUTE

SYSDEF_MSG_DONTROUTE: int

SYSDEF_MSG_OOB

SYSDEF_MSG_OOB: int

SYSDEF_MSG_PEEK

SYSDEF_MSG_PEEK: int

TEST_OPTION_ISOLATE_DIRS

TEST_OPTION_ISOLATE_DIRS: str

A value that can be passed as an option to GLib.test_init.

Creates a unique temporary directory for each unit test and uses sets XDG directories to point into subdirectories of it for the duration of the unit test. The directory tree is cleaned up after the test finishes successfully.

Note that this doesn’t take effect until test_run is called, so calls to (for example) get_home_dir will return the system-wide value when made in a test program’s main() function.

The following functions will return subdirectories of the temporary directory when this option is used. The specific subdirectory paths in use are not guaranteed to be stable API — always use a getter function to retrieve them.

The subdirectories may not be created by the test harness; as with normal calls to functions like get_user_cache_dir, the caller must be prepared to create the directory if it doesn’t exist.

TEST_OPTION_NONFATAL_ASSERTIONS

TEST_OPTION_NONFATAL_ASSERTIONS: str

A value that can be passed as an option to GLib.test_init.

If this option is given, assertions will not abort the process, but call test_fail. Equivalent to test_set_nonfatal_assertions.

TEST_OPTION_NO_PRGNAME

TEST_OPTION_NO_PRGNAME: str

A value that can be passed as an option to GLib.test_init.

If this option is given, GLib.test_init will not call set_prgname.

TIME_SPAN_DAY

TIME_SPAN_DAY: int

Evaluates to a time span of one day.

TIME_SPAN_HOUR

TIME_SPAN_HOUR: int

Evaluates to a time span of one hour.

TIME_SPAN_MILLISECOND

TIME_SPAN_MILLISECOND: int

Evaluates to a time span of one millisecond.

TIME_SPAN_MINUTE

TIME_SPAN_MINUTE: int

Evaluates to a time span of one minute.

TIME_SPAN_SECOND

TIME_SPAN_SECOND: int

Evaluates to a time span of one second.

UNICHAR_MAX_DECOMPOSITION_LENGTH

UNICHAR_MAX_DECOMPOSITION_LENGTH: int

The maximum length (in codepoints) of a compatibility or canonical decomposition of a single Unicode character.

This is as defined by Unicode 6.1.

URI_RESERVED_CHARS_GENERIC_DELIMITERS

URI_RESERVED_CHARS_GENERIC_DELIMITERS: str

Generic delimiters characters as defined in RFC 3986. Includes :/?#[]@.

URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS

URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS: str

Subcomponent delimiter characters as defined in RFC 3986. Includes !$&'()*+,;=.

USEC_PER_SEC

USEC_PER_SEC: int

Number of microseconds in one second (1 million). This macro is provided for code readability.

VA_COPY_AS_ARRAY

VA_COPY_AS_ARRAY: int

VERSION_MIN_REQUIRED

VERSION_MIN_REQUIRED: int

A macro that should be defined by the user prior to including the glib.h header. The definition should be one of the predefined GLib version macros: GLIB_VERSION_2_26, GLIB_VERSION_2_28,...

This macro defines the earliest version of GLib that the package is required to be able to compile against.

If the compiler is configured to warn about the use of deprecated functions, then using functions that were deprecated in version VERSION_MIN_REQUIRED or earlier will cause warnings (but using functions deprecated in later releases will not).

WIN32_MSG_HANDLE

WIN32_MSG_HANDLE: int

macro__has_attributenoreturn_ {#constant-macrohas_attribute___noreturn__}

macro__has_attribute___noreturn__: int

macro__has_attribute_ifunc

macro__has_attribute_ifunc: int

macro__has_attribute_no_sanitize_address

macro__has_attribute_no_sanitize_address: int

Callbacks

CacheDestroyFunc

CacheDestroyFunc = Callable[[], None]

CacheDupFunc

CacheDupFunc = Callable[[], int]

CacheNewFunc

CacheNewFunc = Callable[[], int]

ChildWatchFunc

ChildWatchFunc = Callable[[pid: Pid, wait_status: int], None]

ClearHandleFunc

ClearHandleFunc = Callable[[handle_id: int], None]

CompareDataFunc

CompareDataFunc = Callable[[], int]

CompareFunc

CompareFunc = Callable[[], int]

CompletionFunc

CompletionFunc = Callable[[], str]

CompletionStrncmpFunc

CompletionStrncmpFunc = Callable[[s1: str, s2: str, n: int], int]

CopyFunc

CopyFunc = Callable[[src: int], int]

DataForeachFunc

DataForeachFunc = Callable[[key_id: Quark], None]

DestroyNotify

DestroyNotify = Callable[[], None]

DuplicateFunc

DuplicateFunc = Callable[[], int]

EqualFunc

EqualFunc = Callable[[], bool]

EqualFuncFull

EqualFuncFull = Callable[[], bool]

ErrorClearFunc

ErrorClearFunc = Callable[[error: Error], None]

ErrorCopyFunc

ErrorCopyFunc = Callable[[src_error: Error, dest_error: Error], None]

ErrorInitFunc

ErrorInitFunc = Callable[[error: Error], None]

FDSourceFunc

FDSourceFunc = Callable[[fd: int, condition: IOCondition | int], bool]

FreeFunc

FreeFunc = Callable[[], None]

Func

Func = Callable[[], None]

HFunc

HFunc = Callable[[], None]

HRFunc

HRFunc = Callable[[], bool]

HashFunc

HashFunc = Callable[[], int]

HookCheckFunc

HookCheckFunc = Callable[[], bool]

HookCheckMarshaller

HookCheckMarshaller = Callable[[hook: Hook], bool]

HookCompareFunc

HookCompareFunc = Callable[[new_hook: Hook, sibling: Hook], int]

HookFinalizeFunc

HookFinalizeFunc = Callable[[hook_list: HookList, hook: Hook], None]

HookFindFunc

HookFindFunc = Callable[[hook: Hook], bool]

HookFunc

HookFunc = Callable[[], None]

HookMarshaller

HookMarshaller = Callable[[hook: Hook], None]

IOFunc

IOFunc = Callable[[source: IOChannel, condition: IOCondition | int], bool]

LogFunc

LogFunc = Callable[[log_domain: str | None, log_level: LogLevelFlags | int, message: str], None]

LogWriterFunc

LogWriterFunc = Callable[[log_level: LogLevelFlags | int, fields: list[LogField]], LogWriterOutput | int]

NodeForeachFunc

NodeForeachFunc = Callable[[node: Node], None]

NodeTraverseFunc

NodeTraverseFunc = Callable[[node: Node], bool]

OptionArgFunc

OptionArgFunc = Callable[[option_name: str, value: str], bool]

OptionErrorFunc

OptionErrorFunc = Callable[[context: OptionContext, group: OptionGroup], None]

OptionParseFunc

OptionParseFunc = Callable[[context: OptionContext, group: OptionGroup], bool]

PollFunc

PollFunc = Callable[[ufds: PollFD, nfsd: int, timeout_: int], int]

PrintFunc

PrintFunc = Callable[[string: str], None]

RegexEvalCallback

RegexEvalCallback = Callable[[match_info: MatchInfo, result: String], bool]

ScannerMsgFunc

ScannerMsgFunc = Callable[[scanner: Scanner, message: str, error: bool], None]

SequenceIterCompareFunc

SequenceIterCompareFunc = Callable[[a: SequenceIter, b: SequenceIter], int]

SourceDisposeFunc

SourceDisposeFunc = Callable[[source: Source], None]

SourceDummyMarshal

SourceDummyMarshal = Callable[[], None]

SourceFunc

SourceFunc = Callable[[], bool]

SourceFuncsCheckFunc

SourceFuncsCheckFunc = Callable[[source: Source], bool]

SourceFuncsFinalizeFunc

SourceFuncsFinalizeFunc = Callable[[source: Source], None]

SourceFuncsPrepareFunc

SourceFuncsPrepareFunc = Callable[[source: Source], bool]

SourceOnceFunc

SourceOnceFunc = Callable[[], None]

SpawnChildSetupFunc

SpawnChildSetupFunc = Callable[[], None]

TestDataFunc

TestDataFunc = Callable[[], None]

TestFixtureFunc

TestFixtureFunc = Callable[[fixture: int], None]

TestFunc

TestFunc = Callable[[], None]

TestLogFatalFunc

TestLogFatalFunc = Callable[[log_domain: str, log_level: LogLevelFlags | int, message: str], bool]

ThreadFunc

ThreadFunc = Callable[[], int]

TranslateFunc

TranslateFunc = Callable[[str: str], str]

TraverseFunc

TraverseFunc = Callable[[], bool]

TraverseNodeFunc

TraverseNodeFunc = Callable[[node: TreeNode], bool]

VoidFunc

VoidFunc = Callable[[], None]