[Tutor] getattr works sometimes
Steven D'Aprano
steve at pearwood.info
Wed Oct 3 02:39:44 CEST 2012
On 03/10/12 04:20, Tino Dai wrote:
>>> and the get_class class works sometime for finding modules within a
>>> certain directory. If the get_class
>>> doesn't work, it throws an AttributeError.
>>
>> I don't really understand what you mean by this. Can you copy and
>> paste the actual error message (all of it)?
>>
>>>
>>> The module exists in the directory, and I'm trying to debug this. Does
>>> anybody have any hints to go about debug
>>> this?
>>
>
> get_class('etl.transfers.bill_subject') #
> etl.transfers.bill_subject does exist under the transfers directory
> <module 'etl.transfers.bill_subject' from
> './leg_apps/etl/transfers/bill_subject.pyc'>
I don't understand why you are using the get_class function for this.
It is only useful when you don't know the name of the object until
runtime. Since you know the name, I would suggest that using a regular
import is better:
from etl.transfers import bill_subject
Imports also work differently to getattr, and I believe that is where
you are running into trouble. The (wrongly named) get_class function
uses getattr to extract names from a single top-level module. But that's
not what you are trying to do: you are trying to extract modules from
a package.
Use the right tool for the job: you are trying to use a screwdriver when
you need a screwdriver.
My prediction is that *at some point* in your experiments, you have done
something like:
etl.transfers.bill_subject = bill_subject
*or something with the same effect*. Perhaps the "transfers" module
includes one of these lines:
import bill_subject # Python 2.5 or older?
from . import bill_subject
Now bill_subject is an attribute of the transfers module, and getattr can
see it. But you haven't done the same for related_bills, and so getattr
cannot see it.
Instead, use the right tool, import, which is designed for solving your
problem:
from etl.transfers import bill_subject
from etl.transfers import related_bills
should both work, unless you have removed the bill_subject.py and
related_bills.py files from the etl/transfers/ directory.
--
Steven
More information about the Tutor
mailing list