alex,
@alex@moreati.org.uk avatar

I've inherited some Python code that calls import('somepkg.module, fromlist=[''])
Has anyone seen this elsewhere?Is there a significance of an empty string in fromlist?
Current guess is it's a bug, or a workaround for Python 2.4 era behaviour. The code is https://github.com/mitogen-hq/mitogen/blob/798032b979bf5cabf50d3665f113f67cb5b33152/mitogen/core.py#L682, it's been around since the initial commit https://github.com/mitogen-hq/mitogen/blob/6d403481d44cdffb85ee36cc9e01642bcbc447df/mitogen/core.py#L461

alex,
@alex@moreati.org.uk avatar

I'm looking at this because in modern Python it causes sys.meta_path finders to be called with mpf.find_spec('somepkg.module.', ...), (note the trailing fullstop). Which I'm fairly certain is wrong.

alex,
@alex@moreati.org.uk avatar

import(..., fromlist=['']) isn't unique to Mitogen. It's also in imagepy, webpy, cherrypy, and others https://grep.app/search?q=. Most examples use the returned value. I think it's meant as a way to get the leaf module, rather than the top-level package, e.g.
>>> import('xml.dom.minidom')
<module 'xml' from '.../xml/init.py'>
>>> import('xml.dom.minidom', fromlist=[''])
<module 'xml.dom.minidom' from '.../xml/dom/minidom.py'>

alex,
@alex@moreati.org.uk avatar

Historical trivia: import() first appeared in Python 1.2, released April 1995

alex,
@alex@moreati.org.uk avatar

import(..., fromlist['']) is handled by code that swallows the exception. A comment notes "Backwards-compatibility dictates we ignore failed imports triggered by fromlist for modules that don't exist." https://github.com/python/cpython/blob/v3.12.2/Lib/importlib/_bootstrap.py#L1414-L1422 So I think it's a trick that became widespread in early Python (pre 2.x?), enough to be a grudgingly accepted unofficial API. I should specifically handle it as a corner case in Mitogen's find_spec().

_chrismay,
@_chrismay@fosstodon.org avatar

@alex That's what I'm thinking too. I haven't seen "modern" code like that, The closest code I can think of was from the 2.x era.

The documentation says fromlist "gives the names of objects or submodules that should be imported from the module given by name," but I think you already figured that part out.

link: https://docs.python.org/3/library/functions.html#import__

  • All
  • Subscribed
  • Moderated
  • Favorites
  • python
  • kavyap
  • thenastyranch
  • GTA5RPClips
  • tester
  • InstantRegret
  • DreamBathrooms
  • ngwrru68w68
  • magazineikmin
  • everett
  • Youngstown
  • mdbf
  • slotface
  • rosin
  • cisconetworking
  • megavids
  • khanakhh
  • normalnudes
  • osvaldo12
  • cubers
  • tacticalgear
  • Durango
  • ethstaker
  • modclub
  • anitta
  • provamag3
  • Leos
  • JUstTest
  • lostlight
  • All magazines