How can python call a class that is never defined in the code?
-
20-09-2019 - |
Question
I don't know if it is feasable to paste all of the code here but I am looking at the code in this git repo.
If you look at the example they do:
ec2 = EC2('access key id', 'secret key')
...but there is no EC2
class. However, it looks like in libcloud\providers.py
there is a dict that maps the EC2
to the EC2NodeDriver
found in libcloud\drivers\ec2.py
. The correct mapping is calculated by get_driver(provider)
, but that method doesn't appear to be called anywhere.
I am new to python, obviously, but not to programming. I'm not even sure what I should be looking up in the docs to figure this out.
Solution
example.py
includes an import
statement that reads:
from libcloud.drivers import EC2, Slicehost, Rackspace
This means that the EC2
class is imported from the libcloud.drivers
module. However, in this case, libcloud.drivers
is actually a package (a Python package contains modules), which means that EC2
should be defined in a file __init__.py
in libcloud/drivers/
, but it's not. Which means that in this specific case, their example code is actually wrong. (I downloaded the code and got an import error when running example.py
, and as you can see, the file libcloud/drivers/__init__.py
does not contain any definitions at all, least of all an EC2
definition.)
OTHER TIPS
Checking out the libcloud\examples.py might be helpful. I saw this:
from libcloud.drivers import EC2, Slicehost, Rackspace
The python 'import' statement brings in the class from other python module, in this case from the libcloud.drivers module.