Skip to content

Commit

Permalink
Fix bug: top-level script checking should only ignore the frames with…
Browse files Browse the repository at this point in the history
…in `importlib`
  • Loading branch information
hsfzxjy committed Feb 8, 2021
1 parent 168ce4d commit 6e1dfb8
Showing 1 changed file with 39 additions and 7 deletions.
46 changes: 39 additions & 7 deletions lambdex/__init__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,49 @@
import os
import sys

f = sys._getframe(1)
while f.f_code is not None and f.f_code.co_filename.startswith('<'):
f = f.f_back

if f and f.f_code and f.f_code.co_filename.startswith(os.path.dirname(os.__file__)):
def _is_run_as_script():
"""
Check that whether lambdex is run as top-level script.
We iterate from the stack bottom to find the first frame that contains
no 'importlib' string, which should be the importer of lambdex.
If the importer has any system prefixes, we assert that lambdex is run
as top-level script.
"""
import site
from os.path import dirname, abspath

f = sys._getframe(1)
while f is not None \
and f.f_code is not None \
and 'importlib' in f.f_code.co_filename:
f = f.f_back

if not (f or f.f_code):
return False

filename = abspath(f.f_code.co_filename)
for sitepath in site.getsitepackages() + [site.getusersitepackages()]:
prefix = dirname(dirname(dirname(sitepath))) # such as '/usr/local'
if filename.startswith(prefix):
return True

return False


# If run as top-level script, user is happened to use lxfmt.
# We remove CWD from sys.path, so that the files user editting will not
# cause name conflicts with built-in modules.
if _is_run_as_script():
if sys.path and sys.path[0] == os.getcwd():
sys.path = sys.path[1:]
# Otherwise, we import keywords as normal
else:
__all__ = ['def_']
from .keywords import def_
from .keywords import *
from .keywords import __all__

del os, sys, f
del os, sys, _is_run_as_script

__version__ = "0.2.0"

0 comments on commit 6e1dfb8

Please sign in to comment.