Documentation
¶
Overview ¶
Package initconfig ports cpython/Python/preconfig.c and cpython/Python/initconfig.c. It owns PyPreConfig, PyConfig, and the env+CLI+defaults read pipeline that Py_Initialize consumes.
v0.7 lands the preconfig struct and its three initializers. The remaining surface (env-var reader, PyConfig, _PyConfig_Read) lands in tasks 1622-B through 1622-D.
Index ¶
- Constants
- func GetEnv(useEnv int, name string) string
- func GetEnvFlag(useEnv int, flag *int, name string)
- func StrToInt(str string) (int, bool)
- type AllocatorName
- type ConfigInit
- type EnvVars
- type PyConfig
- type PyPreConfig
- type Status
- func ConfigCopy(dst, src *PyConfig) Status
- func ConfigParseCmdline(c *PyConfig, cmdlineWarnopts *[]string) Status
- func ConfigRead(c *PyConfig) Status
- func ConfigReadEnvVars(c *PyConfig) Status
- func StatusErr(msg string) Status
- func StatusExitCode(code int) Status
- func StatusNoMemory() Status
- func StatusOk() Status
- type StatusType
Constants ¶
const IntMaxStrDigitsThreshold = 4300
IntMaxStrDigitsThreshold is the lower bound CPython enforces on sys.set_int_max_str_digits. Mirrors _PY_LONG_DEFAULT_MAX_STR_DIGITS.
CPython: Include/internal/pycore_long.h:155 _PY_LONG_DEFAULT_MAX_STR_DIGITS
const MaxHashSeed = 0xFFFFFFFF
MaxHashSeed is the upper bound on PYTHONHASHSEED, mirroring the CPython MAX_HASH_SEED macro (UINT32_MAX).
CPython: Python/initconfig.c:1738 MAX_HASH_SEED
Variables ¶
This section is empty.
Functions ¶
func GetEnv ¶
GetEnv reads name from the process environment iff useEnv is non-zero and the value is non-empty. Mirrors _Py_GetEnv: the "Python ignores the environment when -E or PYTHONNOENV is in effect" guard lives here.
CPython: Python/preconfig.c:527 _Py_GetEnv
func GetEnvFlag ¶
GetEnvFlag updates *flag from the integer value of the named env variable, but only if that value is greater than the current *flag. Treats unparseable / negative values as 1, which is how CPython models PYTHONDEBUG=text and PYTHONDEBUG=-2.
CPython: Python/preconfig.c:563 _Py_get_env_flag
Types ¶
type AllocatorName ¶
type AllocatorName int
AllocatorName mirrors the PyMemAllocatorName enum. gopy never reads C-level allocator hooks because Go owns allocation; the field is kept on PyPreConfig for shape parity and has no runtime effect.
CPython: Include/cpython/pymem.h:16 PyMemAllocatorName
const ( AllocatorNotSet AllocatorName = 0 AllocatorDefault AllocatorName = 1 AllocatorDebug AllocatorName = 2 AllocatorMalloc AllocatorName = 3 AllocatorMallocDebug AllocatorName = 4 AllocatorPymalloc AllocatorName = 5 AllocatorPymallocDebug AllocatorName = 6 AllocatorMimalloc AllocatorName = 7 AllocatorMimallocDebug AllocatorName = 8 )
type ConfigInit ¶
type ConfigInit int
ConfigInit selects which initializer was used to populate a PyPreConfig. Mirrors _PyConfigInitEnum.
CPython: Include/internal/pycore_initconfig.h:149 _PyConfigInitEnum
const ( // ConfigInitCompat is the legacy "compat" init: every flag stays // at zero/-1 unless the caller writes it. Used by the old // Py_InitializeEx entry points. ConfigInitCompat ConfigInit = 1 // ConfigInitPython is the modern Python init: parse_argv on, // use_environment on, locale coercion + UTF-8 mode left at -1 so // the locale probe decides. ConfigInitPython ConfigInit = 2 // ConfigInitIsolated is the embedded init: parse_argv off, // use_environment off, isolated on, dev_mode off. ConfigInitIsolated ConfigInit = 3 )
type EnvVars ¶
type EnvVars struct {
Home string
Path string
HashSeed string
DontWriteBytecode int
Unbuffered int
UTF8Mode int
Debug int
Verbose int
Optimize int
NoUserSite int
DevMode int
}
EnvVars is the v0.7 snapshot of the PYTHON* variables PyConfig_Read consumes. Each int field uses the CPython tri-state convention where -1 means "not set in the environment" so the caller can layer CLI / explicit writes on top.
CPython: Python/initconfig.c:1846 config_read_env_vars (subset)
func ReadEnvVars ¶
ReadEnvVars walks the PYTHON* variables gopy honors and returns a snapshot. useEnv mirrors PyConfig.use_environment: 0 means ignore the environment entirely (for -E / PYTHONNOENV mode).
The flag-style reads use GetEnvFlag, which leaves the field at its "not set" sentinel when the variable is absent or empty. The string fields fall through to "" on absence.
CPython: Python/initconfig.c:1843 config_read_env_vars
type PyConfig ¶
type PyConfig struct {
ConfigInit ConfigInit
// Init flags.
Isolated int
UseEnvironment int
DevMode int
InstallSignalHandlers int
UseHashSeed int
HashSeed uint64
ParseArgv int
// PYTHON*-mapped flags.
ParserDebug int
Verbose int
OptimizationLevel int
WriteBytecode int
BufferedStdio int
UserSiteDirectory int
Inspect int
Interactive int
Quiet int
BytesWarning int
ImportTime int
CodeDebugRanges int
WarnDefaultEncoding int
SiteImport int
// Argv and option lists.
Argv []string
OrigArgv []string
XOptions []string
WarnOptions []string
// Filesystem + stdio encoding.
FilesystemEncoding string
FilesystemErrors string
StdioEncoding string
StdioErrors string
ConfigureCStdio int
PycachePrefix string
// Path configuration inputs.
ProgramName string
PythonpathEnv string
Home string
Platlibdir string
// Path configuration outputs.
ModuleSearchPathsSet int
ModuleSearchPaths []string
StdlibDir string
Executable string
BaseExecutable string
Prefix string
BasePrefix string
ExecPrefix string
BaseExecPrefix string
PathconfigWarnings int
SafePath int
// Py_Main parameters.
SkipSourceFirstLine int
RunCommand string
RunModule string
RunFilename string
SysPath0 string
// Misc.
IntMaxStrDigits int
UseFrozenModules int
// Private fields. Mirror CPython's leading-underscore names.
InstallImportlib int
InitMain int
// contains filtered or unexported fields
}
PyConfig is the gopy v0.7 subset of the PyConfig struct. Tri-state ints follow CPython: -1 means "not set, ask the env / locale / CLI reader to decide", 0 means off, 1 (or higher) means on.
Fields scoped out of v0.7 (tracemalloc, perf_profiling, faulthandler, dump_refs, malloc_stats, show_ref_count, check_hash_pycs_mode, thread_inherit_context, context_aware_warnings, enable_gil, tlbc_enabled, legacy_windows_stdio, use_system_logger, _is_python_build) land alongside the subsystems that consume them.
CPython: Include/cpython/initconfig.h:134 PyConfig
func (*PyConfig) Clear ¶
func (c *PyConfig) Clear()
Clear releases the heap-backed slices and strings on c. Mirrors PyConfig_Clear: in CPython this frees the wchar_t * fields and the PyWideStringList allocations; in Go we just reset the struct so any downstream references release their backing memory.
CPython: Python/initconfig.c:959 PyConfig_Clear
func (*PyConfig) InitIsolatedConfig ¶
func (c *PyConfig) InitIsolatedConfig()
InitIsolatedConfig is the embedded entry point. Drops every environment- and user-driven knob: isolated on, use_environment off, user_site_directory off, dev_mode off, install_signal_handlers off, use_hash_seed pinned to zero so the seed becomes deterministic, safe_path on, pathconfig_warnings off, int_max_str_digits clamped to the threshold default.
CPython: Python/initconfig.c:1117 PyConfig_InitIsolatedConfig
func (*PyConfig) InitPythonConfig ¶
func (c *PyConfig) InitPythonConfig()
InitPythonConfig is the modern Python entry point: layered defaults plus parse_argv on and configure_c_stdio on.
CPython: Python/initconfig.c:1106 PyConfig_InitPythonConfig
type PyPreConfig ¶
type PyPreConfig struct {
ConfigInit ConfigInit
ParseArgv int
Isolated int
UseEnvironment int
ConfigureLocale int
CoerceCLocale int
CoerceCLocaleWarn int
// LegacyWindowsFSEncoding is read on Windows only. gopy keeps it
// in the struct so callers porting CPython code don't need build
// tags, but the value is ignored on darwin/linux.
LegacyWindowsFSEncoding int
UTF8Mode int
DevMode int
Allocator AllocatorName
}
PyPreConfig is the pre-init configuration: locale, encoding, and allocator decisions that need to fire before PyConfig_Read runs.
Tri-state ints follow the CPython convention: -1 means "ask the caller / locale probe", 0 means off, 1 (or higher) means on.
CPython: Include/cpython/initconfig.h:47 PyPreConfig
func (*PyPreConfig) InitCompatConfig ¶
func (c *PyPreConfig) InitCompatConfig()
InitCompatConfig is the zero+defaults seeding shared by every initializer. Mirrors _PyPreConfig_InitCompatConfig: zero the struct, stamp ConfigInit=Compat, then bump the "ask the caller" knobs to -1.
CPython: Python/preconfig.c:283 _PyPreConfig_InitCompatConfig
func (*PyPreConfig) InitFromPreConfig ¶
func (c *PyPreConfig) InitFromPreConfig(src *PyPreConfig)
InitFromPreConfig seeds c from another PyPreConfig: start from the Python defaults, then copy every field from src on top. Mirrors _PyPreConfig_InitFromPreConfig: PyPreConfig_InitPythonConfig followed by preconfig_copy.
CPython: Python/preconfig.c:349 _PyPreConfig_InitFromPreConfig
func (*PyPreConfig) InitIsolatedConfig ¶
func (c *PyPreConfig) InitIsolatedConfig()
InitIsolatedConfig is the embedded entry point: locale untouched, isolated on, environment ignored, UTF-8 mode + dev_mode forced off.
CPython: Python/preconfig.c:333 PyPreConfig_InitIsolatedConfig
func (*PyPreConfig) InitPythonConfig ¶
func (c *PyPreConfig) InitPythonConfig()
InitPythonConfig is the modern Python entry point. Layered on top of compat: parse_argv on, use_environment on, isolated explicitly off, locale coercion + UTF-8 mode left at -1 so the locale probe decides at PreConfig.Read time.
CPython: Python/preconfig.c:312 PyPreConfig_InitPythonConfig
type Status ¶
type Status struct {
Type StatusType
Func string
ErrMsg string
ExitCode int
}
Status is the return type lifecycle helpers carry: ok, error with a message, or exit with a code. Mirrors PyStatus.
The Func and ErrMsg fields are written by helpers that set an error so callers can format consistent diagnostics.
CPython: Include/cpython/initconfig.h:10 PyStatus
func ConfigCopy ¶
ConfigCopy clones src into dst. Used by pyinit_core to take a private copy of the caller's config before reading env-vars and CLI args, so subsequent ConfigRead writes do not leak back through shared slice headers.
Mirrors CPython's spec-table walk: every int and string field gets a value copy, every []string gets a fresh backing array.
CPython: Python/initconfig.c:1232 _PyConfig_Copy
func ConfigParseCmdline ¶
ConfigParseCmdline walks c.Argv applying the short and long options CPython's getopt accepts and stamping the corresponding PyConfig fields. Unknown options return an exit-2 status, which matches CPython's "print usage, exit" behavior.
On success c.RunCommand / c.RunModule / c.RunFilename and the option-derived fields (parser_debug, write_bytecode, optimization level, ...) are populated; warnoptions seen on the command line land in cmdlineWarnopts, the caller stitches them into c.WarnOptions in the right order.
CPython: Python/initconfig.c:2865 config_parse_cmdline
func ConfigRead ¶
ConfigRead applies the env-vars, the CLI args, and the layered defaults to c. Mirrors _PyConfig_Read: pre-init bridge, argv copy, isolated-mode forced flips, env-var read, CLI parse, default fallthrough.
The caller seeds c via PyConfig.InitPythonConfig (or InitIsolatedConfig) and stamps any explicit overrides before calling ConfigRead. After ConfigRead returns OK, c is in a consistent state ready for pyinit_core to consume.
Resolution order:
- Environment variables (only when use_environment is set).
- Command-line arguments.
- Layered defaults for any field still at its tri-state -1 sentinel.
Explicit writes by the caller win over both env and CLI: env reads only fill empty string slots, CLI options use ++ for counters that merge with existing values, and default fallthrough only flips -1 sentinels.
CPython: Python/initconfig.c:3471 _PyConfig_Read
func ConfigReadEnvVars ¶
ConfigReadEnvVars merges PYTHON* environment variables into c. Only runs when c.UseEnvironment is non-zero. The flag-style variables (PYTHONDEBUG, PYTHONVERBOSE, ...) feed through GetEnvFlag, which honors the "smaller does not lower" rule. The string-style variables (PYTHONHOME, PYTHONPATH, PYTHONPLATLIBDIR) only overwrite their PyConfig slot if it is empty so explicit writes survive.
CPython: Python/initconfig.c:1839 config_read_env_vars
func StatusErr ¶
StatusErr builds an error Status carrying msg.
CPython: Python/initconfig.c PyStatus_Error
func StatusExitCode ¶
StatusExitCode builds an exit Status with the given code.
CPython: Python/initconfig.c PyStatus_Exit
func StatusNoMemory ¶
func StatusNoMemory() Status
StatusNoMemory builds the "memory allocation failed" Status. gopy rarely hits this because Go owns allocation, but the helper is kept for shape parity with PyStatus_NoMemory.
CPython: Python/initconfig.c PyStatus_NoMemory
func StatusOk ¶
func StatusOk() Status
StatusOk returns the success Status.
CPython: Python/initconfig.c PyStatus_Ok
func (Status) IsError ¶
IsError reports whether s is an error Status.
CPython: Python/initconfig.c PyStatus_IsError
func (Status) IsException ¶
IsException reports whether s is either an error or an exit, the "did the call abort early" check the lifecycle phases run after every step.
CPython: Python/initconfig.c PyStatus_Exception
type StatusType ¶
type StatusType int
StatusType discriminates Status values: ok, error (with message), or exit (with code).
CPython: Include/cpython/initconfig.h:11 _PyStatus_TYPE_*
const ( StatusOK StatusType = 0 StatusError StatusType = 1 StatusExit StatusType = 2 )