55from importlib .machinery import SOURCE_SUFFIXES , ModuleSpec
66from os .path import join
77from types import ModuleType
8- from typing import TYPE_CHECKING
8+ from typing import TYPE_CHECKING , Dict
99
1010from fsspec import url_to_fs
1111from fsspec .implementations .local import AbstractFileSystem
@@ -26,7 +26,11 @@ class FSSpecImportFinder(MetaPathFinder):
2626 def __init__ (self , fsspec : str , ** fsspec_args : str ) -> None :
2727 self .fsspec_fs : AbstractFileSystem
2828 self .root : str
29- self .fsspec_fs , self .root = url_to_fs (fsspec , ** fsspec_args )
29+ if isinstance (fsspec , AbstractFileSystem ):
30+ self .fsspec_fs = fsspec
31+ self .root = fsspec_args .get ("fo" , fsspec .root_marker )
32+ else :
33+ self .fsspec_fs , self .root = url_to_fs (fsspec , ** fsspec_args )
3034 self .remote_modules : dict [str , str ] = {}
3135
3236 def find_spec (self , fullname : str , path : Sequence [str | bytes ] | None , target : ModuleType | None = None ) -> ModuleSpec | None :
@@ -49,7 +53,7 @@ def unload(self) -> None:
4953
5054
5155# Singleton for use elsewhere
52- _finder : FSSpecImportFinder = None
56+ _finders : Dict [ str , FSSpecImportFinder ] = {}
5357
5458
5559class FSSpecImportLoader (SourceLoader ):
@@ -77,18 +81,30 @@ def install_importer(fsspec: str, **fsspec_args: str) -> FSSpecImportFinder:
7781 fsspec: fsspec filesystem string
7882 Returns: The finder instance that was installed.
7983 """
80- global _finder
81- if _finder is None :
82- _finder = FSSpecImportFinder (fsspec , ** fsspec_args )
84+ if isinstance (fsspec , AbstractFileSystem ):
85+ # Reassemble fsspec and args
86+ fsspec = f"{ fsspec .protocol if isinstance (fsspec .protocol , str ) else fsspec .protocol [0 ]} ://{ fsspec .root_marker } "
87+ fsspec_args = fsspec_args or {}
8388
84- sys .meta_path .insert (0 , _finder )
85- return _finder
89+ global _finders
90+ if fsspec in _finders :
91+ return _finders [fsspec ]
92+ _finders [fsspec ] = FSSpecImportFinder (fsspec , ** fsspec_args )
93+ sys .meta_path .insert (0 , _finders [fsspec ])
94+ return _finders [fsspec ]
8695
8796
88- def uninstall_importer () -> None :
97+ def uninstall_importer (fsspec : str = "" ) -> None :
8998 """Uninstall the fsspec importer."""
90- global _finder
91- if _finder is not None and _finder in sys .meta_path :
92- _finder .unload ()
93- sys .meta_path .remove (_finder )
94- _finder = None
99+ global _finders
100+ if not fsspec :
101+ # clear last
102+ if not _finders :
103+ return
104+ fsspec = list (_finders .keys ())[- 1 ]
105+ if fsspec in _finders :
106+ finder = _finders [fsspec ]
107+ del _finders [fsspec ]
108+ if finder in sys .meta_path :
109+ finder .unload ()
110+ sys .meta_path .remove (finder )
0 commit comments