[Python-ideas] __first__ method

Christopher Barker pythonchb at gmail.com
Thu Feb 14 11:32:47 EST 2019


I forstthpughthgegoal here was to avoid imports that may not be needed if
the class isn’t actually used. If that’s the case, then it’s better to
simply put classes with heavyweight imports in their own module.

And:


class Bar(object):
>     def __first__():
>         import math
>     def __init__(self, n):
>         self.a = math.log(2, n)
>

This would bring “math” into the __first__ function’s local namespace, and
it would not be accessible in other methods anyway.

You could put that import line in __init__, or, if needed in other methods,
in __init__:

Import math
self.math = math

Then it wouldn’t get imported until the first instance was created.

But this is generally not considered good style.

I have, occasionally, imported heavy weight modules in optional, rarely
used, methods so that they aren’t imported (or even need to be there) if
they aren’t needed.

-CHB
-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190214/b27d6aef/attachment.html>


More information about the Python-ideas mailing list