Convert a name in the filesystem to the name of the Python module it is. This is aggressive about getting a module name back from a file; it will always return a string. Aggressive means 'sometimes wrong'; it won't look at the Python path or try to do any error checking: don't use
(fn)
| 311 | |
| 312 | |
| 313 | def filenameToModuleName(fn): |
| 314 | """ |
| 315 | Convert a name in the filesystem to the name of the Python module it is. |
| 316 | |
| 317 | This is aggressive about getting a module name back from a file; it will |
| 318 | always return a string. Aggressive means 'sometimes wrong'; it won't look |
| 319 | at the Python path or try to do any error checking: don't use this method |
| 320 | unless you already know that the filename you're talking about is a Python |
| 321 | module. |
| 322 | |
| 323 | @param fn: A filesystem path to a module or package; C{bytes} on Python 2, |
| 324 | C{bytes} or C{unicode} on Python 3. |
| 325 | |
| 326 | @return: A hopefully importable module name. |
| 327 | @rtype: C{str} |
| 328 | """ |
| 329 | if isinstance(fn, bytes): |
| 330 | initPy = b"__init__.py" |
| 331 | else: |
| 332 | initPy = "__init__.py" |
| 333 | fullName = os.path.abspath(fn) |
| 334 | base = os.path.basename(fn) |
| 335 | if not base: |
| 336 | # this happens when fn ends with a path separator, just skit it |
| 337 | base = os.path.basename(fn[:-1]) |
| 338 | modName = nativeString(os.path.splitext(base)[0]) |
| 339 | while 1: |
| 340 | fullName = os.path.dirname(fullName) |
| 341 | if os.path.exists(os.path.join(fullName, initPy)): |
| 342 | modName = "{}.{}".format( |
| 343 | nativeString(os.path.basename(fullName)), |
| 344 | nativeString(modName), |
| 345 | ) |
| 346 | else: |
| 347 | break |
| 348 | return modName |
| 349 | |
| 350 | |
| 351 | def qual(clazz: type[object]) -> str: |