Buck: allow_unsafe_import()
Support Ukraine. Help Provide Humanitarian Aid to Ukraine.

allow_unsafe_import()

Buck has restrictions on importing arbitrary Python modules in build files which make it harder to accidentally violate assumptions about determinism of build files and build rules. The allow_unsafe_import() function may be used to create a context that lifts the restrictions on module importing.

Using this function should be avoided, and done carefully when necessary. Buck's internal caches invalidate build files based on known inputs, and using arbitrary Python code can introduce nondeterministic behavior or inputs that Buck won't know about.

Whitelist and safe versions

Some modules can be imported in a normal way (without using allow_unsafe_import()) because they were whitelisted or a safe version was configured. After checking if they are safe to use in build files, more modules (e.g. local ones) can be added to the whitelist using build_file_import_whitelist config setting.
Whitelistcopy, re, functools, itertools, json, hashlib, types, string, ast, __future__, collections, operator, fnmatch
In the safe versions of modules only selected parts can be used.
ModuleAvailable parts
osenviron, getenv, path, sep, pathsep, linesep
os.pathbasename, commonprefix, dirname, isabs, join, normcase, relpath, split, splitdrive, splitext, sep, pathsep
pipesquote

Examples

Buck has no way to know if the results of uncontrolled file system or network access change, and will not reevaluate the build file if that happens.
import copy # whitelisted
import os   # safe version will be imported
with allow_unsafe_import():
    from os.path import isfile
    import httplib

# Warning! Buck will not detect that the existence of file A affects
# the results of the parsing. The build file will not be processed
# again when A is added/removed.
if isfile(A):
    foo()
else:
    bar()