1

This has always been a source of confusion for me: importing Axes3D (just some sort of python object for our purposes here) appears to change an unrelated function, add_subplot, from a different module. How can that happen? Doesn't that violate the whole idea of namespaces?

What I mean is:

>>> import matplotlib.pyplot as plt
>>> f = plt.figure()
>>> ax = f.add_subplot(111, projection='3d')
# Fails with ValueError: Unknown projection '3d'
>>> from mpl_toolkits.mplot3d import Axes3D
>>> ax = f.add_subplot(111, projection='3d')
# Works!

At first I thought it was similar to from __future__ import print_function, which then somehow magically introduces a function called print into the namespace. But as it turns out, that is in fact magic, and is specific to the __future__ module.

So, how does Axes3D work?

Community
  • 1
  • 1
Praveen
  • 6,872
  • 3
  • 43
  • 62
  • 1
    It looks like [_monkey patching_](http://stackoverflow.com/questions/5626193/what-is-a-monkey-patch) to me... that is the initialization of the `Axes3D` module injects their code into into the target classes. – rodrigo Jan 25 '16 at 19:26
  • @rodrigo Is that really a pythonic way of doing things? Ideally, I'd like to be able to make out what's going on when I read the import statements: I import a module that has some functions and classes (which in turn could support more functions), etc... I then use those functions in my code. And this enables me to go back and introspect those modules' internals. – Praveen Jan 25 '16 at 19:29
  • Okay, so it *is* [thought to be evil](http://stackoverflow.com/a/5626255/525169)... – Praveen Jan 25 '16 at 19:31
  • Maybe it is not the most Pythoning thing, but hey, it gets the work done. Although personally, in your example I'd just use free functions. – rodrigo Jan 25 '16 at 19:33

0 Answers0