77import importlib
88import inspect
99import os
10- import pkgutil
1110import sys
11+ import typing
1212import typing as t
1313
1414import yaml
@@ -391,13 +391,16 @@ def cast_leaves(d, schema):
391391 return value
392392
393393
394+ @typing .no_type_check
394395def get_root_path (import_name : str ) -> str :
395396 """Copied from Flask:
396397 https://github.com/pallets/flask/blob/836866dc19218832cf02f8b04911060ac92bfc0b/src/flask/helpers.py#L595
397398
398399 Find the root path of a package, or the path that contains a
399400 module. If it cannot be found, returns the current working
400401 directory.
402+
403+ :meta private:
401404 """
402405 # Module already imported and has a file attribute. Use that first.
403406 mod = sys .modules .get (import_name )
@@ -406,16 +409,24 @@ def get_root_path(import_name: str) -> str:
406409 return os .path .dirname (os .path .abspath (mod .__file__ ))
407410
408411 # Next attempt: check the loader.
409- loader = pkgutil .get_loader (import_name )
412+ try :
413+ spec = importlib .util .find_spec (import_name )
414+
415+ if spec is None :
416+ raise ValueError
417+ except (ImportError , ValueError ):
418+ loader = None
419+ else :
420+ loader = spec .loader
410421
411422 # Loader does not exist or we're referring to an unloaded main
412423 # module or a main module without path (interactive sessions), go
413424 # with the current working directory.
414- if loader is None or import_name == "__main__" :
425+ if loader is None :
415426 return os .getcwd ()
416427
417428 if hasattr (loader , "get_filename" ):
418- filepath = loader .get_filename (import_name ) # type : ignore
429+ filepath = loader .get_filename (import_name ) # pyright : ignore
419430 else :
420431 # Fall back to imports.
421432 __import__ (import_name )
@@ -436,7 +447,7 @@ def get_root_path(import_name: str) -> str:
436447 )
437448
438449 # filepath is import_name.py for a module, or __init__.py for a package.
439- return os .path .dirname (os .path .abspath (filepath ))
450+ return os .path .dirname (os .path .abspath (filepath )) # type: ignore[no-any-return]
440451
441452
442453def inspect_function_arguments (function : t .Callable ) -> t .Tuple [t .List [str ], bool ]:
@@ -499,7 +510,7 @@ def __init__(self, path: str) -> None:
499510 self .path_regex , _ , _ = compile_path (self .path )
500511
501512 def __lt__ (self , other : "SortableRoute" ) -> bool :
502- return bool (other .path_regex .match (self .path ))
513+ return bool (other .path_regex .match (self .path )) or self . path < other . path
503514
504515 return sorted (routes , key = lambda r : SortableRoute (key (r ) if key else r ))
505516
@@ -542,5 +553,9 @@ def build_example_from_schema(schema):
542553 except ImportError :
543554 return None
544555
545- faker = JSF (schema )
546- return faker .generate ()
556+ try :
557+ faker = JSF (schema )
558+ return faker .generate ()
559+ except TypeError :
560+
561+ return None
0 commit comments