Functions
- access(filename: str, 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().
Added in version 2.8.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
mode – as in access()
- Returns:
zero if the pathname refers to an existing file system object that has all the tested permissions, or -1 otherwise or on error.
- aligned_alloc(n_blocks: int, n_block_bytes: int, alignment: 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()
oraligned_free()
.Added in version 2.72.
- 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*)
- Returns:
the allocated memory
- aligned_alloc0(n_blocks: int, n_block_bytes: int, alignment: int) None
This function is similar to
aligned_alloc()
, but it will also clear the allocated memory before returning it.Added in version 2.72.
- 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*)
- Returns:
the allocated, cleared memory
- aligned_free(mem: None) None
Frees the memory allocated by
aligned_alloc()
.Added in version 2.72.
- Parameters:
mem – the memory to deallocate
- aligned_free_sized(mem: None, alignment: int, size: int) None
Frees the memory pointed to by
mem
, assuming it is has the givensize
andalignment
.If
mem
isNone
this is a no-op (andsize
is ignored).It is an error if
size
doesn’t match the size, oralignment
doesn’t match the alignment, passed whenmem
was allocated.size
andalignment
are passed to this function to allow optimizations in the allocator. If you don’t know either of them, usealigned_free()
instead.Added in version 2.76.
- Parameters:
mem – the memory to free
alignment – alignment of
mem
size – size of
mem
, in bytes
- 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
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
- Returns:
the numerical value of
c
if it is a decimal digit,-1
otherwise
- 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 thanASCII_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
- Returns:
the pointer to the buffer with the converted string
- 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 aprintf()
-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 agdouble
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 convertingd – the value to convert
- Returns:
the pointer to the buffer with the converted string
- 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
ands2
must be non-NULL
.- Parameters:
s1 – string to compare with
s2
s2 – string to compare with
s1
- Returns:
0 if the strings match, a negative value if
s1
<s2
, or a positive value ifs1
>s2
- 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
ifstr
is nul-terminated
- Returns:
a newly-allocated string, with all the upper case characters in
str
converted to lower case. (Note that this is unlike the oldstrdown
, which modified the string in place.)
- 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 givenbase
that is within inclusive bounds limited bymin
andmax
. If this is true, then the converted number is stored inout_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 beINVALID
. If the parsed number is out of bounds -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.Added in version 2.54.
- Parameters:
str – a string to convert
base – base of a parsed number
min – a lower bound (inclusive)
max – an upper bound (inclusive)
- Returns:
true if
str
was a number, false otherwise
- 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 givenbase
that is within inclusive bounds limited bymin
andmax
. If this is true, then the converted number is stored inout_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 beINVALID
. If the parsed number is out of bounds -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.Added in version 2.54.
- Parameters:
str – a string
base – base of a parsed number
min – a lower bound (inclusive)
max – an upper bound (inclusive)
- Returns:
true if
str
was a number, false otherwise
- ascii_strncasecmp(s1: str, s2: str, n: int) int
Compare
s1
ands2
, ignoring the case of ASCII characters and any characters after the firstn
in each string. If either string is less thann
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
- Returns:
0 if the strings match, a negative value if
s1
<s2
, or a positive value ifs1
>s2
- 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), andERANGE
is stored inerrno
. If the correct value would cause underflow, zero is returned andERANGE
is stored inerrno
.This function resets
errno
before callingstrtod()
so that you can reliably detect overflow and underflow.- Parameters:
nptr – the string to convert to a numeric value
- Returns:
the converted value
- 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
orMININT64
is returned, andERANGE
is stored inerrno
. If the base is outside the valid range, zero is returned, andEINVAL
is stored inerrno
. If the string conversion fails, zero is returned, andendptr
returnsnptr
(ifendptr
is non-NULL
).Added in version 2.12.
- Parameters:
nptr – the string to convert to a numeric value
base – to be used for the conversion, 2..36 or 0
- Returns:
the converted value, or zero on error
- 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 aguint64
. 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, andERANGE
is stored inerrno
. If the base is outside the valid range, zero is returned, andEINVAL
is stored inerrno
. If the string conversion fails, zero is returned, andendptr
returnsnptr
(ifendptr
is non-NULL
).Added in version 2.2.
- Parameters:
nptr – the string to convert to a numeric value
base – to be used for the conversion, 2..36 or 0
- Returns:
the converted value, or zero on error
- 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
ifstr
is nul-terminated
- Returns:
a newly-allocated string, with all the lower case characters in
str
converted to upper case. (Note that this is unlike the oldstrup
, which modified the string in place.)
- 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 onEOF
but no need to worry about casting toguchar
before passing a possibly non-ASCII character in.- Parameters:
c – any character
- Returns:
the result of the conversion
- 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 onEOF
but no need to worry about casting toguchar
before passing a possibly non-ASCII character in.- Parameters:
c – any character
- Returns:
the result of the conversion
- 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
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
- Returns:
the numerical value of
c
if it is a hex digit,-1
otherwise
- assert_warning(log_domain: str, file: str, line: int, pretty_function: str, expression: str) None
- Parameters:
log_domain
file
line
pretty_function
expression
- assertion_message(domain: str, file: str, line: int, func: str, message: str) None
- Parameters:
domain
file
line
func
message
- assertion_message_cmpint(domain: str, file: str, line: int, func: str, expr: str, arg1: int, cmp: str, arg2: int, numtype: int) None
- Parameters:
domain
file
line
func
expr
arg1
cmp
arg2
numtype
- assertion_message_cmpstr(domain: str, file: str, line: int, func: str, expr: str, arg1: str, cmp: str, arg2: str) None
- Parameters:
domain
file
line
func
expr
arg1
cmp
arg2
- assertion_message_cmpstrv(domain: str, file: str, line: int, func: str, expr: str, arg1: str, arg2: str, first_wrong_idx: int) None
- Parameters:
domain
file
line
func
expr
arg1
arg2
first_wrong_idx
- assertion_message_error(domain: str, file: str, line: int, func: str, expr: str, error: GError, error_domain: int, error_code: int) None
- Parameters:
domain
file
line
func
expr
error
error_domain
error_code
- atexit(func: Callable[[], None]) None
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 callsatexit()
, 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 whenatexit()
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.Deprecated since version 2.32: It is best to avoid
atexit()
.- Parameters:
func – the function to call on normal program termination.
- atomic_int_add(atomic: int, val: int) int
Atomically adds
val
to the value ofatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
int
orguint
val – the value to add
- Returns:
the value of
atomic
before the add, signed
- atomic_int_and(atomic: int, val: int) int
Performs an atomic bitwise ‘and’ of the value of
atomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.30.
- Parameters:
atomic – a pointer to a
int
orguint
val – the value to ‘and’
- Returns:
the value of
atomic
before the operation, unsigned
- atomic_int_compare_and_exchange(atomic: int, oldval: int, newval: int) bool
Compares
atomic
tooldval
and, if equal, sets it tonewval
. Ifatomic
was not equal tooldval
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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
int
orguint
oldval – the value to compare with
newval – the value to conditionally replace with
- Returns:
True
if the exchange took place
- atomic_int_compare_and_exchange_full(atomic: int, oldval: int, newval: int) tuple[bool, int]
Compares
atomic
tooldval
and, if equal, sets it tonewval
. Ifatomic
was not equal tooldval
then no change occurs. In any case the value ofatomic
before this operation is stored inpreval
.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()
Added in version 2.74.
- Parameters:
atomic – a pointer to a
int
orguint
oldval – the value to compare with
newval – the value to conditionally replace with
- Returns:
True
if the exchange took place
- atomic_int_dec_and_test(atomic: int) 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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
int
orguint
- Returns:
True
if the resultant value is zero
- atomic_int_exchange(atomic: int, newval: int) int
Sets the
atomic
tonewval
and returns the old value fromatomic
.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.
Added in version 2.74.
- Parameters:
atomic – a pointer to a
int
orguint
newval – the value to replace with
- Returns:
the value of
atomic
before the exchange, signed
- atomic_int_exchange_and_add(atomic: int, val: int) int
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.Added in version 2.4.
Deprecated since version 2.30: Use
atomic_int_add()
instead.- Parameters:
atomic – a pointer to a
int
val – the value to add
- Returns:
the value of
atomic
before the add, signed
- atomic_int_get(atomic: int) int
Gets the current value of
atomic
.This call acts as a full compiler and hardware memory barrier (before the get).
While
atomic
has avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
int
orguint
- Returns:
the value of the integer
- atomic_int_inc(atomic: int) 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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
int
orguint
- atomic_int_or(atomic: int, val: int) int
Performs an atomic bitwise ‘or’ of the value of
atomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.30.
- Parameters:
atomic – a pointer to a
int
orguint
val – the value to ‘or’
- Returns:
the value of
atomic
before the operation, unsigned
- atomic_int_set(atomic: int, newval: int) None
Sets the value of
atomic
tonewval
.This call acts as a full compiler and hardware memory barrier (after the set).
While
atomic
has avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
int
orguint
newval – a new value to store
- atomic_int_xor(atomic: int, val: int) int
Performs an atomic bitwise ‘xor’ of the value of
atomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.30.
- Parameters:
atomic – a pointer to a
int
orguint
val – the value to ‘xor’
- Returns:
the value of
atomic
before the operation, unsigned
- atomic_pointer_add(atomic: None, val: int) int
Atomically adds
val
to the value ofatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.In GLib 2.80, the return type was changed from
gssize
toint
to add support for platforms with 128-bit pointers. This should not affect existing code.Added in version 2.30.
- Parameters:
atomic – a pointer to a
gpointer
-sized valueval – the value to add
- Returns:
the value of
atomic
before the add, signed
- atomic_pointer_and(atomic: None, val: int) int
Performs an atomic bitwise ‘and’ of the value of
atomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.In GLib 2.80, the return type was changed from
gsize
toguintptr
to add support for platforms with 128-bit pointers. This should not affect existing code.Added in version 2.30.
- Parameters:
atomic – a pointer to a
gpointer
-sized valueval – the value to ‘and’
- Returns:
the value of
atomic
before the operation, unsigned
- atomic_pointer_compare_and_exchange(atomic: None, oldval: None, newval: None) bool
Compares
atomic
tooldval
and, if equal, sets it tonewval
. Ifatomic
was not equal tooldval
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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
gpointer
-sized valueoldval – the value to compare with
newval – the value to conditionally replace with
- Returns:
True
if the exchange took place
- atomic_pointer_compare_and_exchange_full(atomic: None, oldval: None, newval: None) tuple[bool, None]
Compares
atomic
tooldval
and, if equal, sets it tonewval
. Ifatomic
was not equal tooldval
then no change occurs. In any case the value ofatomic
before this operation is stored inpreval
.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()
Added in version 2.74.
- Parameters:
atomic – a pointer to a
gpointer
-sized valueoldval – the value to compare with
newval – the value to conditionally replace with
- Returns:
True
if the exchange took place
- atomic_pointer_exchange(atomic: None, newval: None) None
Sets the
atomic
tonewval
and returns the old value fromatomic
.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.
Added in version 2.74.
- Parameters:
atomic – a pointer to a
gpointer
-sized valuenewval – the value to replace with
- Returns:
the value of
atomic
before the exchange
- atomic_pointer_get(atomic: None) None
Gets the current value of
atomic
.This call acts as a full compiler and hardware memory barrier (before the get).
While
atomic
has avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
gpointer
-sized value- Returns:
the value of the pointer
- atomic_pointer_or(atomic: None, val: int) int
Performs an atomic bitwise ‘or’ of the value of
atomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.In GLib 2.80, the return type was changed from
gsize
toguintptr
to add support for platforms with 128-bit pointers. This should not affect existing code.Added in version 2.30.
- Parameters:
atomic – a pointer to a
gpointer
-sized valueval – the value to ‘or’
- Returns:
the value of
atomic
before the operation, unsigned
- atomic_pointer_set(atomic: None, newval: None) None
Sets the value of
atomic
tonewval
.This call acts as a full compiler and hardware memory barrier (after the set).
While
atomic
has avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.Added in version 2.4.
- Parameters:
atomic – a pointer to a
gpointer
-sized valuenewval – a new value to store
- atomic_pointer_xor(atomic: None, val: int) int
Performs an atomic bitwise ‘xor’ of the value of
atomic
andval
, storing the result back inatomic
.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 avolatile
qualifier, this is a historical artifact and the pointer passed to it should not bevolatile
.In GLib 2.80, the return type was changed from
gsize
toguintptr
to add support for platforms with 128-bit pointers. This should not affect existing code.Added in version 2.30.
- Parameters:
atomic – a pointer to a
gpointer
-sized valueval – the value to ‘xor’
- Returns:
the value of
atomic
before the operation, unsigned
- atomic_rc_box_acquire(mem_block: None) None
Atomically acquires a reference on the data pointed by
mem_block
.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- Returns:
a pointer to the data, with its reference count increased
- atomic_rc_box_alloc(block_size: int) None
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.
Added in version 2.58.
- Parameters:
block_size – the size of the allocation, must be greater than 0
- Returns:
a pointer to the allocated memory
- atomic_rc_box_alloc0(block_size: int) None
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.
Added in version 2.58.
- Parameters:
block_size – the size of the allocation, must be greater than 0
- Returns:
a pointer to the allocated memory
- atomic_rc_box_dup(block_size: int, mem_block: None) None
Allocates a new block of data with atomic reference counting semantics, and copies
block_size
bytes ofmem_block
into it.Added in version 2.58.
- Parameters:
block_size – the number of bytes to copy, must be greater than 0
mem_block – the memory to copy
- Returns:
a pointer to the allocated memory
- atomic_rc_box_get_size(mem_block: None) int
Retrieves the size of the reference counted data pointed by
mem_block
.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- Returns:
the size of the data, in bytes
- atomic_rc_box_release(mem_block: None) 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
.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- atomic_rc_box_release_full(mem_block: None, clear_func: Callable[[None], None]) 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 ofmem_block
, and then will free the resources allocated formem_block
.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
clear_func – a function to call when clearing the data
- base64_decode(text: str) bytes
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.
Added in version 2.12.
- Parameters:
text – zero-terminated string with base64 text to decode
- Returns:
newly allocated buffer containing the binary data that
text
represents. The returned buffer must be freed withfree()
.
- base64_decode_inplace() tuple[int, bytes]
Decode a sequence of Base-64 encoded text into binary data by overwriting the input data.
Added in version 2.20.
- Returns:
The binary data that
text
responds. This pointer is the same as the inputtext
.
- base64_encode(data: Sequence[int] | None = None) str
Encode a sequence of binary data into its Base-64 stringified representation.
Added in version 2.12.
- Parameters:
data – the binary data to encode
- Returns:
a newly allocated, zero-terminated Base-64 encoded string representing
data
. The returned string must be freed withfree()
.
- base64_encode_close(break_lines: bool) tuple[int, bytes, 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.Added in version 2.12.
- Parameters:
break_lines – whether to break long lines
- Returns:
The number of bytes of output that was written
- base64_encode_step(in_: Sequence[int], break_lines: bool) tuple[int, bytes, 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 withLF
characters, notCR LF
sequences, so the result cannot be passed directly to SMTP or certain other protocols.Added in version 2.12.
- Parameters:
in
break_lines – whether to break long lines
- Returns:
The number of bytes of output that was written
- basename(file_name: str) str
Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.
Deprecated since version 2.2: Use
path_get_basename()
instead, but notice thatpath_get_basename()
allocates new memory for the returned string, unlike this function which returns a pointer into the argument.- Parameters:
file_name – the name of the file
- Returns:
the name of the file without any leading directory components
- bit_lock(address: int, lock_bit: int) None
Sets the indicated
lock_bit
inaddress
. If the bit is already set, this call will block untilbit_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
). Ifbit
is not between 0 and 31 then the result is undefined.This function accesses
address
atomically. All other accesses toaddress
must be atomic in order for this function to work reliably. Whileaddress
has avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.Added in version 2.24.
- Parameters:
address – a pointer to an integer
lock_bit – a bit value between 0 and 31
- 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, setnth_bit
to -1.- Parameters:
mask – a
gulong
containing flagsnth_bit – the index of the bit to start the search from
- Returns:
the index of the first bit set which is higher than
nth_bit
, or -1 if no higher bits are set
- 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, setnth_bit
to-1 or GLIB_SIZEOF_LONG * 8.
- Parameters:
mask – a
gulong
containing flagsnth_bit – the index of the bit to start the search from
- Returns:
the index of the first bit set which is lower than
nth_bit
, or -1 if no lower bits are set
- bit_storage(number: int) int
Gets the number of bits used to hold
number
, e.g. ifnumber
is 4, 3 bits are needed.- Parameters:
number – a
guint
- Returns:
the number of bits used to hold
number
- bit_trylock(address: int, lock_bit: int) bool
Sets the indicated
lock_bit
inaddress
, returningTrue
if successful. If the bit is already set, returnsFalse
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
). Ifbit
is not between 0 and 31 then the result is undefined.This function accesses
address
atomically. All other accesses toaddress
must be atomic in order for this function to work reliably. Whileaddress
has avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.Added in version 2.24.
- Parameters:
address – a pointer to an integer
lock_bit – a bit value between 0 and 31
- Returns:
True
if the lock was acquired
- bit_unlock(address: int, lock_bit: int) None
Clears the indicated
lock_bit
inaddress
. If another thread is currently blocked inbit_lock()
on this same bit then it will be woken up.This function accesses
address
atomically. All other accesses toaddress
must be atomic in order for this function to work reliably. Whileaddress
has avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.Added in version 2.24.
- Parameters:
address – a pointer to an integer
lock_bit – a bit value between 0 and 31
- build_filenamev(args: Sequence[str]) str
Creates a filename from a vector of elements using the correct separator for the current platform.
This function behaves exactly like
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.Added in version 2.8.
- Parameters:
args –
None
-terminated array of strings containing the path elements.- Returns:
the newly allocated path
- build_pathv(separator: str, args: Sequence[str]) str
Behaves exactly like
build_path()
, but takes the path elements as a string array, instead of variadic arguments.This function is mainly meant for language bindings.
Added in version 2.8.
- Parameters:
separator – a string used to separator the elements of the path.
args –
None
-terminated array of strings containing the path elements.
- Returns:
a newly-allocated string that must be freed with
free()
.
- byte_array_remove_range(array: Sequence[int], index_: int, length: int) bytes
- Parameters:
array
index
length
- byte_array_sort(array: Sequence[int], compare_func: Callable[[None, None], int]) None
- Parameters:
array
compare_func
- byte_array_sort_with_data(array: Sequence[int], compare_func: Callable[[...], int], *user_data: Any) None
- Parameters:
array
compare_func
user_data
- canonicalize_filename(filename: str, relative_to: str | None = None) str
Gets the canonical file name from
filename
. All triple slashes are turned into single slashes, and all..
and.
’s resolved againstrelative_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 tofilename
to make it absolute.relative_to
must be an absolute path, orNone
. Ifrelative_to
isNone
, it’ll fallback toget_current_dir()
.This function never fails, and will canonicalize file paths even if they don’t exist.
No file system I/O is done.
Added in version 2.58.
- Parameters:
filename – the name of the file
relative_to – the relative directory, or
None
to use the current working directory
- Returns:
a newly allocated string with the canonical file path
- chdir(path: str) 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().
Added in version 2.8.
- Parameters:
path – a pathname in the GLib file name encoding (UTF-8 on Windows)
- Returns:
0 on success, -1 if an error occurred.
- 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.)Added in version 2.6.
- Parameters:
required_major – the required major version
required_minor – the required minor version
required_micro – the required micro version
- Returns:
None
if the GLib library is compatible with the given version, or a string describing the version mismatch. The returned string is owned by GLib and must not be modified or freed.
- checksum_type_get_length(checksum_type: ChecksumType) int
- Parameters:
checksum_type
- child_watch_add(*args, **kwargs)
Sets a function to be called when the child indicated by
pid
exits, at a default priority,PRIORITY_DEFAULT
.If you obtain
pid
fromspawn_async()
orspawn_async_with_pipes()
you will need to passDO_NOT_REAP_CHILD
as flag to the spawn function for the child watching to work.Note that on platforms where
Pid
must be explicitly closed (seespawn_close_pid()
)pid
must not be closed while the source is still active. Typically, you will want to callspawn_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 usingattach()
. You can do these steps manually if you need greater control.Added in version 2.4.
- Parameters:
args
kwargs
- Returns:
the ID (greater than 0) of the event source.
- child_watch_source_new(pid: int) Source
Creates a new child_watch source.
The source will not initially be associated with any
MainContext
and must be added to one withattach()
before it will be executed.Note that child watch sources can only be used in conjunction with
g_spawn...
when theDO_NOT_REAP_CHILD
flag is used.Note that on platforms where
Pid
must be explicitly closed (seespawn_close_pid()
)pid
must not be closed while the source is still active. Typically, you will want to callspawn_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 processpid
must be positivethe application must not call
waitpid
with a non-positive first argument, for instance in another threadthe application must not wait for
pid
to exit by any other mechanism, includingwaitpid(pid, ...)
or a second child-watch source for the samepid
the application must not ignore
SIGCHLD
Before 2.78, the application could not send a signal (
kill()
) to the watchedpid
in a race free manner. Since 2.78, you can do that while the associatedMainContext
is acquired.Before 2.78, even after destroying the
Source
, you could not be sure thatpid
wasn’t already reaped. Hence, it was also not safe tokill()
orwaitpid()
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 bywaitpid
.Calling
waitpid
for specific processes other thanpid
remains a valid thing to do.Added in version 2.4.
- Parameters:
pid – process to watch. On POSIX the positive pid of a child process. On Windows a handle for a process (which doesn’t have to be a child).
- Returns:
the newly-created child watch source
- chmod(filename: str, 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().
Added in version 2.8.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
mode – as in chmod()
- Returns:
0 if the operation succeeded, -1 on error
- clear_error() None
If
err
or *err
isNone
, does nothing. Otherwise, callsfree()
on *err
and sets *err
toNone
.
- 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 aError
inerror
. 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
isNone
andfd
is a valid open file descriptor. This makes it safe to call from a signal handler or aSpawnChildSetupFunc
under those conditions. See`signal(7)
<man:signal(7>`_) and`signal-safety(7)
<man:signal-safety(7>`_) for more details.Added in version 2.36.
- Parameters:
fd – A file descriptor
- Returns:
True
on success,False
if there was an error.
- 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 BSDclosefrom (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
GLib.SpawnChildSetupFunc
, as long aslowfd
is non-negative. See`signal(7)
<man:signal(7>`_) and`signal-safety(7)
<man:signal-safety(7>`_) for more details.Added in version 2.80.
- Parameters:
lowfd – Minimum fd to close, which must be non-negative
- Returns:
0 on success, -1 with errno set on error
- compute_checksum_for_bytes(checksum_type: ChecksumType, data: Bytes) str | None
Computes the checksum for a binary
data
. This is a convenience wrapper fornew()
,get_string()
andfree()
.The hexadecimal string returned will be in lower case.
Added in version 2.34.
- Parameters:
checksum_type – a
ChecksumType
data – binary blob to compute the digest of
- Returns:
the digest of the binary data as a string in hexadecimal, or
None
ifnew()
fails forchecksum_type
. The returned string should be freed withfree()
when done using it.
- compute_checksum_for_data(checksum_type: ChecksumType, data: Sequence[int]) str | None
Computes the checksum for a binary
data
oflength
. This is a convenience wrapper fornew()
,get_string()
andfree()
.The hexadecimal string returned will be in lower case.
Added in version 2.16.
- Parameters:
checksum_type – a
ChecksumType
data – binary blob to compute the digest of
- Returns:
the digest of the binary data as a string in hexadecimal, or
None
ifnew()
fails forchecksum_type
. The returned string should be freed withfree()
when done using it.
- compute_checksum_for_string(checksum_type: ChecksumType, str: str, length: int) str | None
Computes the checksum of a string.
The hexadecimal string returned will be in lower case.
Added in version 2.16.
- 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.
- Returns:
the checksum as a hexadecimal string, or
None
ifnew()
fails forchecksum_type
. The returned string should be freed withfree()
when done using it.
- compute_hmac_for_bytes(digest_type: ChecksumType, key: Bytes, data: Bytes) str
Computes the HMAC for a binary
data
. This is a convenience wrapper fornew()
,get_string()
andunref()
.The hexadecimal string returned will be in lower case.
Added in version 2.50.
- Parameters:
digest_type – a
ChecksumType
to use for the HMACkey – the key to use in the HMAC
data – binary blob to compute the HMAC of
- Returns:
the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with
free()
when done using it.
- compute_hmac_for_data(digest_type: ChecksumType, key: Sequence[int], data: Sequence[int]) str
Computes the HMAC for a binary
data
oflength
. This is a convenience wrapper fornew()
,get_string()
andunref()
.The hexadecimal string returned will be in lower case.
Added in version 2.30.
- Parameters:
digest_type – a
ChecksumType
to use for the HMACkey – the key to use in the HMAC
data – binary blob to compute the HMAC of
- Returns:
the HMAC of the binary data as a string in hexadecimal. The returned string should be freed with
free()
when done using it.
- compute_hmac_for_string(digest_type: ChecksumType, key: Sequence[int], str: str, length: int) str
Computes the HMAC for a string.
The hexadecimal string returned will be in lower case.
Added in version 2.30.
- Parameters:
digest_type – a
ChecksumType
to use for the HMACkey – 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
- Returns:
the HMAC as a hexadecimal string. The returned string should be freed with
free()
when done using it.
- convert(str: Sequence[int], to_codeset: str, from_codeset: str) tuple[bytes, int]
Converts a string from one character set to another.
Note that you should use
()
for streaming conversions. Despite the fact thatbytes_read
can return information about partial characters, theg_convert_...
functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won’t be preserved across successive calls toconvert()
,convert_with_iconv()
orconvert_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
.
- Returns:
If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with
free()
. OtherwiseNone
anderror
will be set.
- convert_with_fallback(str: Sequence[int], to_codeset: str, from_codeset: str, fallback: str) tuple[bytes, 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 fromfrom_codeset
toto_codeset
in their iconv() functions, in which case GLib will simply return that approximate conversion.Note that you should use
()
for streaming conversions. Despite the fact thatbytes_read
can return information about partial characters, theg_convert_...
functions are not generally suitable for streaming. If the underlying converter maintains internal state, then this won’t be preserved across successive calls toconvert()
,convert_with_iconv()
orconvert_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.
- Returns:
If the conversion was successful, a newly allocated buffer containing the converted string, which must be freed with
free()
. OtherwiseNone
anderror
will be set.
- creat(filename: str, 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().
Added in version 2.8.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
mode – as in creat()
- Returns:
a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from creat().
- datalist_foreach(datalist: Data, func: Callable[[...], None], *user_data: Any) None
Calls the given function for each data element of the datalist. The function is called with each data element’s
Quark
id and data, together with the givenuser_data
parameter. Note that this function is NOT thread-safe. So unlessdatalist
can be protected from any modifications during invocation of this function, it should not be called.func
can make changes todatalist
, but the iteration will not reflect changes made during thedatalist_foreach()
call, other than skipping over elements that are removed.- Parameters:
datalist – a datalist.
func – the function to call for each data element.
user_data – user data to pass to the function.
- datalist_get_data(datalist: Data, key: str) 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.
- Returns:
the data element, or
None
if it is not found.
- datalist_get_flags(datalist: Data) int
Gets flags values packed in together with the datalist. See
datalist_set_flags()
.Added in version 2.8.
- Parameters:
datalist – pointer to the location that holds a list
- Returns:
the flags of the datalist
- datalist_id_get_data(datalist: Data, key_id: int) None
Retrieves the data element corresponding to
key_id
.- Parameters:
datalist – a datalist.
key_id – the
Quark
identifying a data element.
- Returns:
the data element, or
None
if it is not found.
- datalist_id_remove_multiple(datalist: Data, keys: Sequence[int]) None
Removes multiple keys from a datalist.
This is more efficient than calling
datalist_id_remove_data()
multiple times in a row.Before 2.80,
n_keys
had to be not larger than 16. Now it can be larger, but note that GData does a linear search, so an excessive number of keys will perform badly.Added in version 2.74.
- Parameters:
datalist – a datalist
keys – keys to remove
- 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
type, for example.)Added in version 2.8.
- 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 forflags
that doesn’t fit within the mask is an error.
- datalist_unset_flags(datalist: Data, flags: int) None
Turns off flag values for a data list. See
datalist_unset_flags()
Added in version 2.8.
- 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 forflags
that doesn’t fit within the mask is an error.
- dataset_destroy(dataset_location: None) 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(dataset_location: None, func: Callable[[...], None], *user_data: Any) 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 thedataset_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.
user_data – user data to pass to the function.
- dataset_id_get_data(dataset_location: None, key_id: int) None
Gets the data element corresponding to a
Quark
.- Parameters:
dataset_location – the location identifying the dataset.
key_id – the
Quark
id to identify the data element.
- Returns:
the data element corresponding to the
Quark
, orNone
if it is not found.
- date_valid_weekday(weekday: DateWeekday) bool
- Parameters:
weekday
- dcgettext(domain: str | None, msgid: str, category: int) str
This is a variant of
dgettext()
that allows specifying a locale category instead of always usingLC_MESSAGES
. Seedgettext()
for more information about how this functions differs from calling dcgettext() directly.Added in version 2.26.
- Parameters:
domain – the translation domain to use, or
None
to use the domain set with textdomain()msgid – message to translate
category – a locale category
- Returns:
the translated string for the given locale category
- 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 notNone
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.
Added in version 2.18.
- Parameters:
domain – the translation domain to use, or
None
to use the domain set with textdomain()msgid – message to translate
- Returns:
The translated string
- direct_equal(v1: None, v2: None) bool
Compares two
gpointer
arguments and returnsTrue
if they are equal. It can be passed tonew()
as thekey_equal_func
parameter, when using opaque pointers compared by pointer value as keys in aHashTable
.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
- Returns:
True
if the two keys match.
- direct_hash(v: None) int
Converts a gpointer to a hash value. It can be passed to
new()
as thehash_func
parameter, when using opaque pointers compared by pointer value as keys in aHashTable
.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- Returns:
a hash value corresponding to the key.
- 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.Added in version 2.18.
- 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
- Returns:
The translated string
- double_equal(v1: None, v2: None) bool
Compares the two
float
values being pointed to and returnsTrue
if they are equal. It can be passed tonew()
as thekey_equal_func
parameter, when using non-None
pointers to doubles as keys in aHashTable
.Added in version 2.22.
- double_hash(v: None) int
Converts a pointer to a
float
to a hash value. It can be passed tonew()
as thehash_func
parameter, It can be passed tonew()
as thehash_func
parameter, when using non-None
pointers to doubles as keys in aHashTable
.Added in version 2.22.
- Parameters:
v – a pointer to a
float
key- Returns:
a hash value corresponding to the key.
- 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 inmsgctxtid
. If 0 is passed asmsgidoffset
, 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.
Added in version 2.16.
- 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
- Returns:
The translated string
- 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 inmsgctxtid
.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.
Added in version 2.18.
- Parameters:
domain – the translation domain to use, or
None
to use the domain set with textdomain()context – the message context
msgid – the message
- Returns:
The translated string
- environ_getenv(envp: Sequence[str] | None, variable: str) str | None
Returns the value of the environment variable
variable
in the provided listenvp
.Added in version 2.32.
- Parameters:
envp – an environment list (eg, as returned from
get_environ()
), orNone
for an empty environment listvariable – the environment variable to get
- Returns:
the value of the environment variable, or
None
if the environment variable is not set inenvp
. The returned string is owned byenvp
, and will be freed ifvariable
is set or unset again.
- environ_setenv(envp: Sequence[str] | None, variable: str, value: str, overwrite: bool) list[str]
Sets the environment variable
variable
in the provided listenvp
tovalue
.Added in version 2.32.
- Parameters:
envp – an environment list that can be freed using
strfreev()
(e.g., as returned fromget_environ()
), orNone
for an empty environment listvariable – 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
- Returns:
the updated environment list. Free it using
strfreev()
.
- environ_unsetenv(envp: Sequence[str] | None, variable: str) list[str]
Removes the environment variable
variable
from the provided environmentenvp
.Added in version 2.32.
- Parameters:
envp – an environment list that can be freed using
strfreev()
(e.g., as returned fromget_environ()
), orNone
for an empty environment listvariable – the environment variable to remove, must not contain ‘=’
- Returns:
the updated environment list. Free it using
strfreev()
.
- error_domain_register(error_type_name: str, error_type_private_size: int, error_type_init: Callable[[GError], None], error_type_copy: Callable[[GError, GError], None], error_type_clear: Callable[[GError], None]) int
- Parameters:
error_type_name
error_type_private_size
error_type_init
error_type_copy
error_type_clear
- error_domain_register_static(error_type_name: str, error_type_private_size: int, error_type_init: Callable[[GError], None], error_type_copy: Callable[[GError, GError], None], error_type_clear: Callable[[GError], None]) int
- Parameters:
error_type_name
error_type_private_size
error_type_init
error_type_copy
error_type_clear
- fdwalk_set_cloexec(lowfd: int) int
Mark every file descriptor equal to or greater than
lowfd
to be closed at the nextexecve()
or similar, as if via theFD_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
GLib.SpawnChildSetupFunc
, as long aslowfd
is non-negative. See`signal(7)
<man:signal(7>`_) and`signal-safety(7)
<man:signal-safety(7>`_) for more details.Added in version 2.80.
- Parameters:
lowfd – Minimum fd to act on, which must be non-negative
- Returns:
0 on success, -1 with errno set on error
- file_error_from_errno(err_no: int) FileError
Gets a
FileError
constant based on the passed-inerr_no
.For example, if you pass in
EEXIST
this function returnsEXIST
. Unlikeerrno
values, you can portably assume that allFileError
values will exist.Normally a
FileError
value goes into aError
returned from a function that manipulates files. So you would usefile_error_from_errno()
when constructing aError
.- Parameters:
err_no – an “errno” value
- Returns:
FileError
corresponding to the givenerr_no
- file_get_contents(filename: str) tuple[bool, bytes]
Reads an entire file into allocated memory, with good error checking.
If the call was successful, it returns
True
and setscontents
to the file contents andlength
to the length of the file contents in bytes. The string stored incontents
will be nul-terminated, so for text files you can passNone
for thelength
argument. If the call was not successful, it returnsFalse
and setserror
. The error domain is%G_FILE_ERROR
. Possible error codes are those in theFileError
enumeration. In the error case,contents
is set toNone
andlength
is set to zero.- Parameters:
filename – name of a file to read contents from, in the GLib file name encoding
- Returns:
True
on success,False
if an error occurred
- file_open_tmp(tmpl: str | None = 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 tomkstemp()
. However, unlike these functions, the template should only be a basename, no directory components are allowed. If template isNone
, a default template is used.Note that in contrast to
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 inname_used
. This string should be freed withfree()
when not needed any longer. The returned name is in the GLib file name encoding.- Parameters:
tmpl – Template for file name, as in
mkstemp()
, basename only, orNone
for a default template- Returns:
A file handle (as from open()) to the file opened for reading and writing. The file is opened in binary mode on platforms where there is a difference. The file handle should be closed with close(). In case of errors, -1 is returned and
error
will be set.
- file_read_link(filename: str) str
Reads the contents of the symbolic link
filename
like the POSIXreadlink()
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
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); }
Added in version 2.4.
- Parameters:
filename – the symbolic link
- Returns:
A newly-allocated string with the contents of the symbolic link, or
None
if an error occurred.
- file_set_contents(filename: str, contents: Sequence[int]) bool
Writes all of
contents
to a file namedfilename
. This is a convenience wrapper around callingfile_set_contents_full()
withflags
set toG_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING
andmode
set to0666
.Added in version 2.8.
- Parameters:
filename – name of a file to write
contents
to, in the GLib file name encodingcontents – string to write to the file
- Returns:
True
on success,False
if an error occurred
- file_set_contents_full(filename: str, contents: Sequence[int], flags: FileSetContentsFlags, mode: int) bool
Writes all of
contents
to a file namedfilename
, with good error checking. If a file calledfilename
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 thanNONE
then this function may callfsync()
.If
CONSISTENT
is set inflags
, 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 tofilename
will break. Also since the file is recreated, existing permissions, access control lists, metadata etc. may be lost. Iffilename
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 ifCONSISTENT
is set inflags
, thefsync()
call (or equivalent) will be used to ensure atomic replacement:filename
will contain either its old contents orcontents
, 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 leavefilename
empty or full of NUL bytes, depending on the underlying filesystem, unlessDURABLE
andCONSISTENT
are set inflags
.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 returnsFalse
and setserror
. The error domain is%G_FILE_ERROR
. Possible error codes are those in theFileError
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 may be changed tomode
depending onflags
, or they may remain unchanged.Added in version 2.66.
- Parameters:
filename – name of a file to write
contents
to, in the GLib file name encodingcontents – 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 be0666
- Returns:
True
on success,False
if an error occurred
- file_test(filename: str, test: FileTest) bool
Returns
True
if any of the tests in the bitfieldtest
areTrue
. For example,(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)
will returnTrue
if the file exists; the check whether it’s a directory doesn’t matter since the existence test isTrue
. With the current set of available tests, there’s no point passing in more than one test at a time.Apart from
IS_SYMLINK
all tests follow symbolic links, so for a symbolic link to a regular filefile_test()
will returnTrue
for bothIS_SYMLINK
andIS_REGULAR
.Note, that for a dangling symbolic link
file_test()
will returnTrue
forIS_SYMLINK
andFalse
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
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
EXISTS
andIS_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
IS_SYMLINK
will always returnFalse
. Testing forIS_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 thePATHEXT
environment variable.- Parameters:
filename – a filename to test in the GLib file name encoding
test – bitfield of
FileTest
flags
- Returns:
whether a test was
True
- filename_display_basename(filename: str) 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 “357277275” in octal notation) to find out iffilename
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.Added in version 2.6.
- Parameters:
filename – an absolute pathname in the GLib file name encoding
- Returns:
a newly allocated string containing a rendition of the basename of the filename in valid UTF-8
- filename_display_name(filename: str) 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 “357277275” in octal notation) to find out iffilename
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.Added in version 2.6.
- Parameters:
filename – a pathname hopefully in the GLib file name encoding
- Returns:
a newly allocated string containing a rendition of the filename in valid UTF-8
- 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).
- Returns:
a newly-allocated string holding the resulting filename, or
None
on an error.
- filename_from_utf8(utf8string, len=-1)
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][setlocale].
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 errorILLEGAL_SEQUENCE
. If the filename encoding is not UTF-8 and the conversion output contains a nul character, the errorEMBEDDED_NUL
is set and the function returnsNone
.- Parameters:
utf8string – a UTF-8 encoded string.
len – the length of the string, or -1 if the string is nul-terminated.
- Returns:
The converted string, or
None
on an error.
- filename_to_uri(filename: str, hostname: str | None = 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.
- Returns:
a newly-allocated string holding the resulting URI, or
None
on an error.
- filename_to_utf8(opsysstring: str, 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][setlocale].
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 errorILLEGAL_SEQUENCE
. If the source encoding is not UTF-8 and the conversion output contains a nul character, the errorEMBEDDED_NUL
is set and the function returnsNone
. Useconvert()
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)
- Returns:
The converted string, or
None
on an error.
- find_program_in_path(program: str) 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, orNone
if the program is not found in the path. Ifprogram
is already an absolute path, returns a copy ofprogram
ifprogram
exists and is executable, andNone
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 thePATHEXT
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
- Returns:
a newly-allocated string with the absolute path, or
None
- fopen(filename: str, mode: str) None
A wrapper for the stdio
fopen()
function. Thefopen()
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, theFILE*
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 likefprintf()
orfread()
.See your C library manual for more details about
fopen()
.As
close()
andfclose()
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 likefile_set_contents_full()
avoid this problem.Added in version 2.6.
- 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
- Returns:
A
FILE*
if the file was successfully opened, orNone
if an error occurred
- 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.Added in version 2.30.
- Parameters:
size – a size in bytes
- Returns:
a newly-allocated formatted string containing a human readable file size
- format_size_for_display(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.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.Added in version 2.16.
Deprecated since version 2.30: This function is broken due to its use of SI suffixes to denote IEC units. Use
format_size()
instead.- Parameters:
size – a size in bytes
- Returns:
a newly-allocated formatted string containing a human readable file size
- format_size_full(size: int, flags: FormatSizeFlags) str
Formats a size.
This function is similar to
format_size()
but allows for flags that modify the output. SeeFormatSizeFlags
.Added in version 2.30.
- Parameters:
size – a size in bytes
flags –
FormatSizeFlags
to modify the output
- Returns:
a newly-allocated formatted string containing a human readable file size
- free(mem: None) None
Frees the memory pointed to by
mem
.If you know the allocated size of
mem
, callingfree_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()
](https://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html) to understand its caveats).If
mem
isNone
it simply returns, so there is no need to checkmem
againstNone
before calling this function.- Parameters:
mem – the memory to free
- free_sized(mem: None, size: int) None
Frees the memory pointed to by
mem
, assuming it is has the givensize
.If
mem
isNone
this is a no-op (andsize
is ignored).It is an error if
size
doesn’t match the size passed whenmem
was allocated.size
is passed to this function to allow optimizations in the allocator. If you don’t know the allocation size, usefree()
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.Added in version 2.76.
- Parameters:
mem – the memory to free
size – size of
mem
, in bytes
- freopen(filename: str, mode: str, stream: None) 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().
Added in version 2.6.
- 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
- Returns:
A FILE* if the file was successfully opened, or
None
if an error occurred.
- 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. Thefsync()
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().
Added in version 2.64.
- Parameters:
fd – a file descriptor
- Returns:
0 on success, or -1 if an error occurred. The return value can be used exactly like the return value from fsync().
- 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 withget_prgname()
, which gets a non-localized name. Ifset_application_name()
has not been called, returns the result ofget_prgname()
(which may beNone
ifset_prgname()
has also not been called).Added in version 2.2.
- Returns:
human-readable application name. May return
None
- get_charset() tuple[bool, str]
Obtains the character set for the [current locale][setlocale]; you might use this character set as an argument to
convert()
, to convert from the current locale’s encoding to some other encoding. (Frequentlylocale_to_utf8()
andlocale_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
andCHARSET
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 callingconvert()
.The string returned in
charset
is not allocated, and should not be freed.- Returns:
True
if the returned charset is UTF-8
- get_codeset() str
Gets the character set for the current locale.
- Returns:
a newly allocated string containing the name of the character set. This string must be freed with
free()
.
- 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 callingconvert()
.The string returned in
charset
is not allocated, and should not be freed.Added in version 2.62.
- Returns:
True
if the returned charset is UTF-8
- 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.
- Returns:
the current directory
- get_current_time()
Equivalent to the UNIX gettimeofday() function, but portable.
You may find
get_real_time()
to be more convenient.Deprecated since version 2.62:
TimeVal
is not year-2038-safe. Useget_real_time()
instead.
- 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.Added in version 2.28.
- Returns:
the list of environment variables
- 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, seefilename_display_name()
.On Unix, the character sets are determined by consulting the environment variables
G_FILENAME_ENCODING
andG_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][setlocale]. IfG_FILENAME_ENCODING
is not set, butG_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.Added in version 2.6.
- Returns:
True
if the filename encoding is UTF-8.
- 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 thepasswd
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 thepasswd
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.- Returns:
the current user’s home directory
- 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.
Added in version 2.8.
- Returns:
the host name of the machine.
- 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
andLANG
to find the list of locales specified by the user.Added in version 2.6.
- Returns:
a
None
-terminated array of strings owned by GLib that must not be modified or freed.
- 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
, andLANG
to find the list of locales specified by the user.get_language_names()
returns g_get_language_names_with_category(“LC_MESSAGES”).Added in version 2.58.
- Parameters:
category_name – a locale category name
- Returns:
a
None
-terminated array of strings owned by the thread g_get_language_names_with_category was called from. It must not be modified or freed. It must be copied if planned to be used in another thread.
- 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)
<man:setlocale>`_ for information about locales and their format.locale
itself is guaranteed to be returned in the output.For example, if
locale
isfr_BE
, then the returned list isfr_BE
,fr
. Iflocale
isen_GB.UTF-8``euro``
, then the returned list isen_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()
.Added in version 2.28.
- Parameters:
locale – a locale identifier
- Returns:
a newly allocated array of newly allocated strings with the locale variants. Free with
strfreev()
.
- get_monotonic_time() int
Queries the system monotonic time.
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.
Added in version 2.28.
- Returns:
the monotonic time, in microseconds
- 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
new()
for CPU bound tasks and similar cases.Added in version 2.36.
- Returns:
Number of schedulable threads, always greater than 0
- 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 isNone
.Added in version 2.64.
- Parameters:
key_name – a key for the OS info being requested, for example
%G_OS_INFO_KEY_NAME
.- Returns:
The associated value for the requested key or
None
if this information is not provided.
- 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
GApplication
the program name is set in g_application_run(). In case of GDK or GTK it is set in gdk_init(), which is called by gtk_init() and theGtkApplication
::startup handler. The program name is found by taking the last component of ``argv``[0].- Returns:
the name of the program, or
None
if it has not been set yet. The returned string belongs to GLib and must not be modified or freed.
- 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.- Returns:
the user’s real name.
- get_real_time() int
Queries the system wall-clock time.
This call is functionally equivalent to
get_current_time()
except that the return value is often more convenient than dealing with aTimeVal
.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.Added in version 2.28.
- Returns:
the number of microseconds since January 1, 1970 UTC.
- 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. IfXDG_CONFIG_DIRS
is undefined, the directory that contains application data for all users is used instead. A typical path isC:Documents and SettingsAll UsersApplication 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.
Added in version 2.6.
- Returns:
a
None
-terminated array of strings owned by GLib that must not be modified or freed.
- 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. IfXDG_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.
Added in version 2.6.
- Returns:
a
None
-terminated array of strings owned by GLib that must not be modified or freed.
- 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.- Returns:
the directory to use for temporary files.
- 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. IfXDG_CACHE_HOME
is undefined, the directory that serves as a common repository for temporary Internet files is used instead. A typical path isC:Documents and SettingsusernameLocal SettingsTemporary Internet Files
. See thedocumentation for ``FOLDERID_InternetCache`
<https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid>`_.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.
Added in version 2.6.
- Returns:
a string owned by GLib that must not be modified or freed.
- 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. IfXDG_CONFIG_HOME
is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See thedocumentation for ``FOLDERID_LocalAppData`
<https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid>`_. Note that in this case on Windows it will be the same as whatget_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.
Added in version 2.6.
- Returns:
a string owned by GLib that must not be modified or freed.
- 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. IfXDG_DATA_HOME
is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See thedocumentation for ``FOLDERID_LocalAppData`
<https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid>`_. Note that in this case on Windows it will be the same as whatget_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.
Added in version 2.6.
- Returns:
a string owned by GLib that must not be modified or freed.
- 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.
- Returns:
the user name of the current user.
- 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 ofget_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.
Added in version 2.28.
- Returns:
a string owned by GLib that must not be modified or freed.
- get_user_special_dir(directory: UserDirectory) 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,
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.
Added in version 2.14.
- Parameters:
directory – the logical id of special directory
- Returns:
the path to the specified special directory, or
None
if the logical id was not found. The returned string is owned by GLib and should not be modified or freed.
- 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. IfXDG_STATE_HOME
is undefined, the folder to use for local (as opposed to roaming) application data is used instead. See thedocumentation for ``FOLDERID_LocalAppData`
<https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid>`_. Note that in this case on Windows it will be the same as whatget_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.
Added in version 2.72.
- Returns:
a string owned by GLib that must not be modified or freed.
- getenv(variable: str) 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
- Returns:
the value of the environment variable, or
None
if the environment variable is not found. The returned string may be overwritten by the next call togetenv()
,setenv()
orunsetenv()
.
- hash_table_find(hash_table: dict[None, None], predicate: Callable[[...], bool], *user_data: Any) None
- Parameters:
hash_table
predicate
user_data
- hash_table_foreach(hash_table: dict[None, None], func: Callable[[...], None], *user_data: Any) None
- Parameters:
hash_table
func
user_data
- hash_table_foreach_remove(hash_table: dict[None, None], func: Callable[[...], bool], *user_data: Any) int
- Parameters:
hash_table
func
user_data
- hash_table_insert(hash_table: dict[None, None], key: None, value: None) bool
- Parameters:
hash_table
key
value
- hash_table_lookup_extended(hash_table: dict[None, None], lookup_key: None) tuple[bool, None, None]
- Parameters:
hash_table
lookup_key
- hash_table_new_similar(other_hash_table: dict[None, None]) dict[None, None]
- Parameters:
other_hash_table
- hash_table_replace(hash_table: dict[None, None], key: None, value: None) bool
- Parameters:
hash_table
key
value
- hook_insert_before(hook_list: HookList, sibling: Hook | None, hook: Hook) None
- Parameters:
hook_list
sibling
hook
- hook_insert_sorted(hook_list: HookList, hook: Hook, func: Callable[[Hook, Hook], int]) None
- Parameters:
hook_list
hook
func
- hostname_is_ascii_encoded(hostname: str) bool
Tests if
hostname
contains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returnsTrue
, you should decode the hostname withhostname_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()
andhostname_is_ascii_encoded()
to both returnTrue
for a name.Added in version 2.22.
- Parameters:
hostname – a hostname
- Returns:
True
ifhostname
contains any ASCII-encoded segments.
- 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).
Added in version 2.22.
- Parameters:
hostname – a hostname (or IP address in string form)
- Returns:
True
ifhostname
is an IP address
- hostname_is_non_ascii(hostname: str) bool
Tests if
hostname
contains Unicode characters. If this returnsTrue
, you need to encode the hostname withhostname_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()
andhostname_is_ascii_encoded()
to both returnTrue
for a name.Added in version 2.22.
- Parameters:
hostname – a hostname
- Returns:
True
ifhostname
contains any non-ASCII characters
- 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.Added in version 2.22.
- Parameters:
hostname – a valid UTF-8 or ASCII hostname
- Returns:
an ASCII hostname, which must be freed, or
None
ifhostname
is in some way invalid.
- 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.Added in version 2.22.
- Parameters:
hostname – a valid UTF-8 or ASCII hostname
- Returns:
a UTF-8 hostname, which must be freed, or
None
ifhostname
is in some way invalid.
- idle_add(function, *user_data, **kwargs)
Adds a function to be called whenever there are no higher priority events pending to the default main loop. The function is given the default idle priority,
PRIORITY_DEFAULT_IDLE
. If the function returnsFalse
it is automatically removed from the list of event sources and will not be called again.See [memory management of sources][mainloop-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 globalMainContext
usingattach()
, 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:
function – function to call
user_data
kwargs
- Returns:
the ID (greater than 0) of the event source.
- idle_remove_by_data(data: None) bool
Removes the idle function with the given data.
- Parameters:
data – the data for the idle source’s callback.
- Returns:
True
if an idle source was found and removed.
- 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 withattach()
before it will be executed. Note that the default priority for idle sources isPRIORITY_DEFAULT_IDLE
, as compared to other sources which have a default priority ofPRIORITY_DEFAULT
.- Returns:
the newly-created idle source
- int64_equal(v1: None, v2: None) bool
Compares the two
int
values being pointed to and returnsTrue
if they are equal. It can be passed tonew()
as thekey_equal_func
parameter, when using non-None
pointers to 64-bit integers as keys in aHashTable
.Added in version 2.22.
- int64_hash(v: None) int
Converts a pointer to a
int
to a hash value.It can be passed to
new()
as thehash_func
parameter, when using non-None
pointers to 64-bit integer values as keys in aHashTable
.Added in version 2.22.
- Parameters:
v – a pointer to a
int
key- Returns:
a hash value corresponding to the key.
- int_equal(v1: None, v2: None) bool
Compares the two
int
values being pointed to and returnsTrue
if they are equal. It can be passed tonew()
as thekey_equal_func
parameter, when using non-None
pointers to integers as keys in aHashTable
.Note that this function acts on pointers to
int
, not onint
directly: if your hash table’s keys are of the formGINT_TO_POINTER (n)
, usedirect_equal()
instead.
- int_hash(v: None) int
Converts a pointer to a
int
to a hash value. It can be passed tonew()
as thehash_func
parameter, when using non-None
pointers to integer values as keys in aHashTable
.Note that this function acts on pointers to
int
, not onint
directly: if your hash table’s keys are of the formGINT_TO_POINTER (n)
, usedirect_hash()
instead.- Parameters:
v – a pointer to a
int
key- Returns:
a hash value corresponding to the key.
- intern_static_string(string: str | None = 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, thereforestring
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++.
Added in version 2.10.
- Parameters:
string – a static string
- Returns:
a canonical representation for the string
- intern_string(string: str | None = 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++.
Added in version 2.10.
- Parameters:
string – a string
- Returns:
a canonical representation for the string
- io_add_watch(*args, **kwargs)
Adds the
IOChannel
into the default main loop context with the default priority.- Parameters:
args
kwargs
- Returns:
the event source id
- io_channel_error_from_errno(en: int) IOChannelError
- Parameters:
en
- io_create_watch(channel: IOChannel, condition: IOCondition) Source
Creates a
Source
that’s dispatched whencondition
is met for the givenchannel
. For example, if condition isIN
, the source will be dispatched when there’s data available for reading.The callback function invoked by the
Source
should be added withset_callback()
, but it has typeIOFunc
(notSourceFunc
).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.
- 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 andgetenv()
provide.Added in version 2.8.
- Returns:
a
None
-terminated list of strings which must be freed withstrfreev()
.
- locale_from_utf8(utf8string: str, len: int) tuple[bytes, 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][setlocale]. 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 errorILLEGAL_SEQUENCE
. Useconvert()
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.
- Returns:
A newly-allocated buffer containing the converted string, or
None
on an error, and error will be set.
- locale_to_utf8(opsysstring: Sequence[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][setlocale] into a UTF-8 string.
If the source encoding is not UTF-8 and the conversion output contains a nul character, the error
EMBEDDED_NUL
is set and the function returnsNone
. If the source encoding is UTF-8, an embedded nul character is treated with theILLEGAL_SEQUENCE
error for backward compatibility with earlier versions of this library. Useconvert()
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.
- Returns:
The converted string, or
None
on an error.
- log_default_handler(log_domain: str | None, log_level: LogLevelFlags, message: str | None, unused_data: None) None
The default log handler set up by 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
orstdout
and if the log level is fatal it callsBREAKPOINT
. It automatically prints a new-line character after the message, so one does not need to be manually included inmessage
.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, uselog_writer_default_set_debug_domains
.
stderr
is used for levelsLEVEL_ERROR
,LEVEL_CRITICAL
,LEVEL_WARNING
andLEVEL_MESSAGE
.stdout
is used for the rest, unlessstderr
was requested bylog_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 domainlog_level – the level of the message
message – the message
unused_data – data passed from
log
which is unused
- 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
debug
or other logging functions; it should only be used fromLogWriterFunc
implementations.Note also that the value of this does not depend on
G_MESSAGES_DEBUG
, norlog_writer_default_set_debug_domains
; see the docs forlog_set_debug_enabled
.Added in version 2.72.
- Returns:
TRUE
if debug output is enabled,FALSE
otherwise
- 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(fatal_mask: LogLevelFlags) 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.
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
log_structured
andlog_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
- Returns:
the old fatal mask
- 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
andlog_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.
Added in version 2.72.
- Parameters:
enabled –
TRUE
to enable debug output,FALSE
otherwise
- log_set_fatal_mask(log_domain: str, fatal_mask: LogLevelFlags) LogLevelFlags
Sets the log levels which are fatal in the given domain.
LEVEL_ERROR
is always fatal.This has no effect on structured log messages (using
log_structured
orlog_structured_array
). To change the fatal behaviour for specific log messages, programs must install a custom log writer function usinglog_set_writer_func
. See Using Structured Logging.This function is mostly intended to be used with
LEVEL_CRITICAL
. You should typically not setLEVEL_WARNING
,LEVEL_MESSAGE
,LEVEL_INFO
orLEVEL_DEBUG
as fatal except inside of test programs.- Parameters:
log_domain – the log domain
fatal_mask – the new fatal mask
- Returns:
the old fatal mask for the log domain
- log_set_handler(log_domain: str | None, log_levels: LogLevelFlags, log_func: Callable[[...], None], *user_data: Any) int
Sets the log handler for a domain and a set of log levels.
To handle fatal and recursive messages the
log_levels
parameter must be combined with theFLAG_FATAL
andFLAG_RECURSION
bit flags.Note that since the
LEVEL_ERROR
log level is always fatal, if you want to set a handler for this log level you must combine it withFLAG_FATAL
.This has no effect if structured logging is enabled; see Using Structured Logging.
Here is an example for adding a log handler for all warning messages in the default domain:
g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
This example adds a log handler for all critical messages from GTK:
g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
This example adds a log handler for all messages from GLib:
g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
- Parameters:
log_domain – the log domain, or
NULL
for the default""
application domainlog_levels – the log levels to apply the log handler for. To handle fatal and recursive messages as well, combine the log levels with the
FLAG_FATAL
andFLAG_RECURSION
bit flags.log_func – the log handler function
user_data – data passed to the log handler
- Returns:
the id of the new handler
- log_set_writer_func(func: Callable[[...], LogWriterOutput] | None = None, *user_data: Any) 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.
Added in version 2.50.
- Parameters:
func – log writer function, which must not be
NULL
user_data – user data to pass to
func
- log_structured_array(log_level: LogLevelFlags, fields: Sequence[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 isLEVEL_ERROR
), the program will be aborted at the end of this function.See
log_structured
for more documentation.This assumes that
log_level
is already present infields
(typically as thePRIORITY
field).Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags
, or a user-defined levelfields – key–value pairs of structured data to add to the log message
- log_variant(log_domain: str | None, log_level: LogLevelFlags, 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 typeG_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 thanG_MAXSSIZE
. Otherwise it will be truncated to this size. For other typesprint
will be used to convert the value into a string.For more details on its usage and about the parameters, see
log_structured
.Added in version 2.50.
- Parameters:
log_domain – log domain, usually
G_LOG_DOMAIN
log_level – log level, either from
LogLevelFlags
, or a user-defined levelfields – a dictionary (
Variant
of the typeG_VARIANT_TYPE_VARDICT
) containing the key-value pairs of message data.
- log_writer_default(log_level: LogLevelFlags, fields: Sequence[LogField], user_data: 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
orstderr
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 usinglog_set_writer_func
.As with
log_default_handler
, this function drops debug and informational messages unless their log domain (orall
) is listed in the space-separatedG_MESSAGES_DEBUG
environment variable, or set at runtime bylog_writer_default_set_debug_domains
.log_writer_default
uses the mask set bylog_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.Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags
, or a user-defined levelfields – key–value pairs of structured data forming the log message
user_data – user data passed to
log_set_writer_func
- Returns:
- log_writer_default_set_debug_domains(domains: str | None = None) None
Reset the list of domains to be logged, that might be initially set by the
G_MESSAGES_DEBUG
environment variable.This function is thread-safe.
Added in version 2.80.
- Parameters:
domains –
NULL
-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(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 bothlog_writer_default
andlog_writer_standard_streams
for the structured API.By default, log messages of levels
LEVEL_INFO
andLEVEL_DEBUG
are sent tostdout
, and other log messages are sent tostderr
. This is problematic for applications that intend to reservestdout
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.
Added in version 2.68.
- Parameters:
use_stderr – If
TRUE
, usestderr
for log messages that would normally have appeared onstdout
- log_writer_default_would_drop(log_level: LogLevelFlags, log_domain: str | None = None) bool
Check whether
log_writer_default
andlog_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 (orall
) is listed in the space-separatedG_MESSAGES_DEBUG
environment variable, or bylog_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`` is not set: ```c if (!g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN)) { g_autofree gchar *result = expensive_computation (my_object); g_debug ("my_object result: ``%s``", result); }
Added in version 2.68.
- Parameters:
log_level – log level, either from
LogLevelFlags
, or a user-defined levellog_domain – log domain
- Returns:
TRUE
if the log message would be dropped by GLib’s default log handlers
- log_writer_format_fields(log_level: LogLevelFlags, fields: Sequence[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
andGLIB_DOMAIN
(see the documentation forlog_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.
Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags
, or a user-defined levelfields – key–value pairs of structured data forming the log message
use_color –
TRUE
to use ANSI color escape sequences when formatting the message,FALSE
to not
- Returns:
string containing the formatted log message, in the character set of the current locale
- 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 orstdout
orstderr
).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));
Added in version 2.50.
- Parameters:
output_fd – output file descriptor to check
- Returns:
TRUE
ifoutput_fd
points to the journal,FALSE
otherwise
- log_writer_journald(log_level: LogLevelFlags, fields: Sequence[LogField], user_data: 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
UNHANDLED
.Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags
, or a user-defined levelfields – key–value pairs of structured data forming the log message
user_data – user data passed to
log_set_writer_func
- Returns:
- log_writer_standard_streams(log_level: LogLevelFlags, fields: Sequence[LogField], user_data: None) LogWriterOutput
Format a structured log message and print it to either
stdout
orstderr
, depending on its log level.LEVEL_INFO
andLEVEL_DEBUG
messages are sent tostdout
, or tostderr
if requested bylog_writer_default_set_use_stderr
; all other log levels are sent tostderr
. 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
.Added in version 2.50.
- Parameters:
log_level – log level, either from
LogLevelFlags
, or a user-defined levelfields – key–value pairs of structured data forming the log message
user_data – user data passed to
log_set_writer_func
- Returns:
- 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.
Added in version 2.50.
- Parameters:
output_fd – output file descriptor to check
- Returns:
TRUE
if ANSI color escapes are supported,FALSE
otherwise
- log_writer_syslog(log_level: LogLevelFlags, fields: Sequence[LogField], user_data: 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
UNHANDLED
.Added in version 2.80.
- Parameters:
log_level – log level, either from
LogLevelFlags
, or a user-defined levelfields – key–value pairs of structured data forming the log message
user_data – user data passed to
log_set_writer_func
- Returns:
- lstat(filename: str, 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 tostat()
.See your C library manual for more details about lstat().
Added in version 2.6.
- 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
- Returns:
0 if the information was successfully retrieved,
-1 if an error occurred
- main_context_default() MainContext
- main_context_get_thread_default() MainContext | None
- main_current_source() Source | None
Returns the currently firing source for this thread.
Added in version 2.12.
- Returns:
The currently firing source or
None
.
- main_depth() int
Returns the depth of the stack of calls to
dispatch()
on anyMainContext
in the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback fromiteration()
(orrun()
, etc.) it returns 1. When called from within a callback to a recursive call toiteration()
, 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 ifmain_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:Use gtk_widget_set_sensitive() or modal dialogs to prevent the user from interacting with elements while the main loop is recursing.
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.
- Returns:
The main loop recursion level in the current thread
- malloc(n_bytes: int) None
Allocates
n_bytes
bytes of memory. Ifn_bytes
is 0 it returnsNone
.If the allocation fails (because the system is out of memory), the program is terminated.
- Parameters:
n_bytes – the number of bytes to allocate
- Returns:
a pointer to the allocated memory
- malloc0(n_bytes: int) None
Allocates
n_bytes
bytes of memory, initialized to 0’s. Ifn_bytes
is 0 it returnsNone
.If the allocation fails (because the system is out of memory), the program is terminated.
- Parameters:
n_bytes – the number of bytes to allocate
- Returns:
a pointer to the allocated memory
- malloc0_n(n_blocks: int, n_block_bytes: 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.
Added in version 2.24.
- Parameters:
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
a pointer to the allocated memory
- malloc_n(n_blocks: int, n_block_bytes: 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.
Added in version 2.24.
- Parameters:
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
a pointer to the allocated memory
- markup_escape_text(text, length=-1)
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 &``x1``; … &``x1f``; 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
- Returns:
a newly allocated string with the escaped text
- mem_is_system_malloc() bool
Checks whether the allocator used by
malloc()
is the system’s malloc implementation. If it returnsTrue
memory allocated with malloc() can be used interchangeably with memory allocated usingmalloc()
. This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.Deprecated since version 2.46: GLib always uses the system malloc, so this function always returns
True
.- Returns:
if
True
, malloc() andmalloc()
can be mixed.
- mem_profile() None
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.
Deprecated since version 2.46: Use other memory profiling tools instead
- mem_set_vtable(vtable: MemVTable) None
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.
Deprecated since version 2.46: This function now does nothing. Use other memory profiling tools instead
- Parameters:
vtable – table of memory allocation routines.
- memdup(mem: None, byte_size: int) None
Allocates
byte_size
bytes of memory, and copiesbyte_size
bytes into it frommem
. Ifmem
isNULL
it returnsNULL
.Deprecated since version 2.68: Use
memdup2
instead, as it accepts a gsize argument forbyte_size
, avoiding the possibility of overflow in agsize
→guint
conversion- Parameters:
mem – the memory to copy
byte_size – the number of bytes to copy
- Returns:
a pointer to the newly-allocated copy of the memory
- memdup2(mem: None, byte_size: int) None
Allocates
byte_size
bytes of memory, and copiesbyte_size
bytes into it frommem
. Ifmem
isNULL
it returnsNULL
.This replaces
memdup
, which was prone to integer overflows when converting the argument from agsize
to aguint
.Added in version 2.68.
- Parameters:
mem – the memory to copy
byte_size – the number of bytes to copy
- Returns:
a pointer to the newly-allocated copy of the memory
- mkdir(filename: str, 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().
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
mode – permissions to use for the newly created directory
- Returns:
0 if the directory was successfully created, -1 if an error occurred
- mkdir_with_parents(pathname: str, mode: int) int
Create a directory if it doesn’t already exist. Create intermediate parent directories as needed, too.
Added in version 2.8.
- Parameters:
pathname – a pathname in the GLib file name encoding
mode – permissions to use for newly created directories
- Returns:
0 if the directory already exists, or was successfully created. Returns -1 if an error occurred, with errno set.
- nullify_pointer(nullify_location: None) None
Set the pointer at the specified location to
None
.- Parameters:
nullify_location – the memory address of the pointer.
- 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 thelog()
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 callingon_error_stack_trace()
instead.- Parameters:
prg_name – the program name, needed by gdb for the “[S]tack trace” option. If
prg_name
isNone
,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(prg_name: str) 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 withget_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 theG_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
- open(filename: str, 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().
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
flags – as in open()
mode – as in open()
- Returns:
a new file descriptor, or -1 if an error occurred. The return value can be used exactly like the return value from open().
- parse_debug_string(string: str | None, keys: Sequence[DebugKey]) int
Parses a string containing debugging options into a unsigned
int
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” instring
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 inkeys
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.
- Returns:
the combined set of bit flags.
- path_get_basename(file_name: str) str
Gets the last component of the filename.
If
file_name
ends with a directory separator it gets the component before the last slash. Iffile_name
consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. Iffile_name
is empty, it gets “.”.- Parameters:
file_name – the name of the file
- Returns:
a newly allocated string containing the last component of the filename
- path_get_dirname(file_name: str) 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
- Returns:
the directory components of the file
- path_is_absolute(file_name: str) bool
Returns
True
if the givenfile_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 “Userstml” or begins with the root on a drive, for example “C:Windows”. The first case also includes UNC paths such as “\\myserverdocsfoo”. 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
- Returns:
True
iffile_name
is absolute
- path_skip_root(file_name: str) str | None
Returns a pointer into
file_name
after the root component, i.e. after the “/” in UNIX or “C:" under Windows. Iffile_name
is not an absolute path it returnsNone
.- Parameters:
file_name – a file name
- Returns:
a pointer into
file_name
after the root component
- 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
new()
and callpattern_match_string()
repeatedly.- Parameters:
pattern – the UTF-8 encoded pattern
string – the UTF-8 encoded string to match
- Returns:
True
ifstring
matchespspec
- pointer_bit_lock(address: None, lock_bit: int) None
This is equivalent to g_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 avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.Added in version 2.30.
- Parameters:
address – a pointer to a
gpointer
-sized valuelock_bit – a bit value between 0 and 31
- pointer_bit_lock_and_get(address: None, lock_bit: int) int
This is equivalent to g_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.
Added in version 2.80.
- Parameters:
address – a pointer to a
gpointer
-sized valuelock_bit – a bit value between 0 and 31
- pointer_bit_lock_mask_ptr(ptr: None, lock_bit: int, set: bool, preserve_mask: int, preserve_ptr: None) None
This mangles
ptr
aspointer_bit_lock()
andpointer_bit_unlock()
do.Added in version 2.80.
- Parameters:
ptr – the pointer to mask
lock_bit – the bit to set/clear. If set to
G_MAXUINT
, the lockbit is taken frompreserve_ptr
orptr
(depending onpreserve_mask
).set – whether to set (lock) the bit or unset (unlock). This has no effect, if
lock_bit
is set toG_MAXUINT
.preserve_mask – if non-zero, a bit-mask for
preserve_ptr
. Thepreserve_mask
bits frompreserve_ptr
are set in the result. Note that thelock_bit
bit will be always set according toset
, regardless ofpreserve_mask
andpreserve_ptr
(unlesslock_bit
isG_MAXUINT
).preserve_ptr – if
preserve_mask
is non-zero, the bits from this pointer are set in the result.
- Returns:
the mangled pointer.
- pointer_bit_trylock(address: None, 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 avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.Added in version 2.30.
- Parameters:
address – a pointer to a
gpointer
-sized valuelock_bit – a bit value between 0 and 31
- Returns:
True
if the lock was acquired
- pointer_bit_unlock(address: None, lock_bit: int) None
This is equivalent to g_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 avolatile
qualifier, this is a historical artifact and the argument passed to it should not bevolatile
.Added in version 2.30.
- Parameters:
address – a pointer to a
gpointer
-sized valuelock_bit – a bit value between 0 and 31
- pointer_bit_unlock_and_set(address: None, lock_bit: int, ptr: 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 havelock_bit
unset. This also means, you usually can only use this on the lowest bits.Added in version 2.80.
- Parameters:
address – a pointer to a
gpointer
-sized valuelock_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 thelock_bit
bit will be always set according toset
, regardless ofpreserve_mask
and the currently set value inaddress
.
- 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 byMainContext
, 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 aPollFD
describing a single file descriptor to poll. Thefd
field indicates the file descriptor, and theevents
field indicates the events to poll for. On return, therevents
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 usepoll()
in code that has to run on Windows, the easiest solution is to construct all of yourPollFD
with g_io_channel_win32_make_pollfd().Added in version 2.20.
- 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
- Returns:
the number of entries in
fds
whoserevents
fields were filled in, or 0 if the operation timed out, or -1 on error or if the call was interrupted.
- prefix_error_literal(prefix: str) GError
Prefixes
prefix
to an existing error message. Iferr
or *err
isNone
(i.e.: no error variable) then do nothing.Added in version 2.70.
- Parameters:
prefix – string to prefix
err
with
- propagate_error(src: GError) GError
If
dest
isNone
, freesrc
; otherwise, movessrc
into *dest
. The error variabledest
points to must beNone
.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 toNone
after calling this function on it.- Parameters:
src – error to move into the return location
- qsort_with_data(pbase: None, total_elems: int, size: int, compare_func: Callable[[...], int], *user_data: Any) None
This is just like the standard C qsort() function, but the comparison routine accepts a user data argument.
This is guaranteed to be a stable sort since version 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
user_data – data to pass to
compare_func
- quark_from_static_string(string: str | None = None) int
Gets the
Quark
identifying the given (static) string. If the string does not currently have an associatedQuark
, a newQuark
is created, linked to the given string.Note that this function is identical to
quark_from_string()
except that if a newQuark
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
- Returns:
the
Quark
identifying the string, or 0 ifstring
isNone
- quark_from_string(string: str | None = None) int
Gets the
Quark
identifying the given string. If the string does not currently have an associatedQuark
, a newQuark
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
- Returns:
the
Quark
identifying the string, or 0 ifstring
isNone
- quark_to_string(quark: int) str
Gets the string associated with the given
Quark
.- Parameters:
quark – a
Quark
.- Returns:
the string associated with the
Quark
- quark_try_string(string: str | None = None) int
Gets the
Quark
associated with the given string, or 0 if string isNone
or it has no associatedQuark
.If you want the GQuark to be created if it doesn’t already exist, use
quark_from_string()
orquark_from_static_string()
.This function must not be used before library constructors have finished running.
- Parameters:
string – a string
- Returns:
the
Quark
associated with the string, or 0 ifstring
isNone
or there is noQuark
associated with it
- random_double() float
Returns a random
float
equally distributed over the range [0..1).- Returns:
a random number
- random_double_range(begin: float, end: float) float
Returns a random
float
equally distributed over the range [begin
..``end``).- Parameters:
begin – lower closed bound of the interval
end – upper open bound of the interval
- Returns:
a random number
- random_int() int
Return a random
guint32
equally distributed over the range [0..2^32-1].- Returns:
a random number
- random_int_range(begin: int, end: int) int
Returns a random
int
equally distributed over the range [begin
..``end``-1].- Parameters:
begin – lower closed bound of the interval
end – upper open bound of the interval
- Returns:
a random number
- 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(mem_block: None) None
Acquires a reference on the data pointed by
mem_block
.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- Returns:
a pointer to the data, with its reference count increased
- rc_box_alloc(block_size: int) None
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.
Added in version 2.58.
- Parameters:
block_size – the size of the allocation, must be greater than 0
- Returns:
a pointer to the allocated memory
- rc_box_alloc0(block_size: int) None
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.
Added in version 2.58.
- Parameters:
block_size – the size of the allocation, must be greater than 0
- Returns:
a pointer to the allocated memory
- rc_box_dup(block_size: int, mem_block: None) None
Allocates a new block of data with reference counting semantics, and copies
block_size
bytes ofmem_block
into it.Added in version 2.58.
- Parameters:
block_size – the number of bytes to copy, must be greater than 0
mem_block – the memory to copy
- Returns:
a pointer to the allocated memory
- rc_box_get_size(mem_block: None) int
Retrieves the size of the reference counted data pointed by
mem_block
.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- Returns:
the size of the data, in bytes
- rc_box_release(mem_block: None) 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
.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
- rc_box_release_full(mem_block: None, clear_func: Callable[[None], None]) 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 ofmem_block
, and then will free the resources allocated formem_block
.Added in version 2.58.
- Parameters:
mem_block – a pointer to reference counted data
clear_func – a function to call when clearing the data
- realloc(mem: None, n_bytes: int) None
Reallocates the memory pointed to by
mem
, so that it now has space forn_bytes
bytes of memory. It returns the new address of the memory, which may have been moved.mem
may beNone
, in which case it’s considered to have zero-length.n_bytes
may be 0, in which caseNone
will be returned andmem
will be freed unless it isNone
.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
- Returns:
the new address of the allocated memory
- realloc_n(mem: None, n_blocks: int, n_block_bytes: 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.
Added in version 2.24.
- Parameters:
mem – the memory to reallocate
n_blocks – the number of blocks to allocate
n_block_bytes – the size of each block in bytes
- Returns:
the new address of the allocated memory
- regex_match_simple(pattern: str, string: str, compile_options: RegexCompileFlags, match_options: RegexMatchFlags) bool
- Parameters:
pattern
string
compile_options
match_options
- regex_split_simple(pattern: str, string: str, compile_options: RegexCompileFlags, match_options: RegexMatchFlags) list[str]
- Parameters:
pattern
string
compile_options
match_options
- 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.Added in version 2.22.
- remove(filename: str) 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().
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
- Returns:
0 if the file was successfully removed, -1 if an error occurred
- rename(oldfilename: str, newfilename: str) 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.
Added in version 2.6.
- Parameters:
oldfilename – a pathname in the GLib file name encoding (UTF-8 on Windows)
newfilename – a pathname in the GLib file name encoding
- Returns:
0 if the renaming succeeded, -1 if an error occurred
- rmdir(filename: str) 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.
Added in version 2.6.
- Parameters:
filename – a pathname in the GLib file name encoding (UTF-8 on Windows)
- Returns:
0 if the directory was successfully removed, -1 if an error occurred
- sequence_foreach_range(begin: SequenceIter, end: SequenceIter, func: Callable[[...], None], *user_data: Any) None
- Parameters:
begin
end
func
user_data
- sequence_get(iter: SequenceIter) None
- Parameters:
iter
- sequence_insert_before(iter: SequenceIter, data: None) SequenceIter
- Parameters:
iter
data
- sequence_move(src: SequenceIter, dest: SequenceIter) None
- Parameters:
src
dest
- sequence_move_range(dest: SequenceIter, begin: SequenceIter, end: SequenceIter) None
- Parameters:
dest
begin
end
- sequence_range_get_midpoint(begin: SequenceIter, end: SequenceIter) SequenceIter
- Parameters:
begin
end
- sequence_remove(iter: SequenceIter) None
- Parameters:
iter
- sequence_remove_range(begin: SequenceIter, end: SequenceIter) None
- Parameters:
begin
end
- sequence_set(iter: SequenceIter, data: None) None
- Parameters:
iter
data
- sequence_sort_changed(iter: SequenceIter, cmp_func: Callable[[...], int], *cmp_data: Any)