Skip to content

Imports

Import forms

import math
import math as m
from math import abs
from math import abs as absolute

Using imported names

import math
def main() -> None:
print(math.abs(-5))
print(math.max(3, 9))
print(math.min(3, 9))

With from:

from math import abs as magnitude
def main() -> None:
print(magnitude(-5))
print(magnitude(-2.5))

Modules and packages

A module is a .p4 file. A package is a directory with an __init__.p4 file.

myproject/
main.p4
utils.p4
models/
__init__.p4
point.p4

Dotted imports:

import pkgdemo
import pkgdemo.math.ops
import pkgdemo.math.ops as ops
from pkgdemo.math.more import shift
def main() -> None:
print(pkgdemo.package_seed)
print(pkgdemo.math.ops.square(5))
print(ops.square(4))
print(shift(10))

Scoping rules

  • import module binds a namespace. Bare names from that module are not available without qualification.
  • from module import name makes name available directly.
  • Imported names do not leak into a flat global namespace.
  • Names prefixed with _ are module-private and cannot be imported.

Module-private names

tools.p4
_seed: int = 5
def _twice(x: int) -> int:
return x * 2
def reveal_total() -> int:
return _twice(_seed)
main.p4
import tools
def main() -> None:
print(tools.reveal_total()) # ok
# print(tools._seed) # compile error — private

Compilation model

All reachable modules are compiled into one C program. There is no separate compilation or link-time module boundary. Imports are a compile-time mechanism, not a runtime module system.