[Tutor] how import a module upon instantiation of a class?

Albert-Jan Roskam fomcl at yahoo.com
Mon Sep 1 15:46:41 CEST 2014



----- Original Message -----




> From: Peter Otten <__peter__ at web.de>
> To: tutor at python.org
> Cc: 
> Sent: Monday, September 1, 2014 1:17 AM
> Subject: Re: [Tutor] how import a module upon instantiation of a class?
> 
> Albert-Jan Roskam wrote:
> 
>>  I want to import a module upon instantiation (not definition) of a class.
>>  What is the best way to do this? In my case, I need the "icu" 
> module in
>>  only one place/class of the program. If that class won't be used, I 
> don't
>>  want to have an ImportError. Also, it might be nice to do the imports only
>>  when you actually need that functionality. It's probably not really
>>  PEP-compliant to put the imports somewhere else than at the top of the
>>  module, but I can live with that.
>> 
>> 
>>  import some_nonbuiltin  # I don't want it here!
>> 
>> 
>>  class KlassA(object):
>>      import some_nonbuiltin  # nope
>> 
>>      def __init__(self):
>           global some_nonbuiltin
>           import some_nonbuiltin


Ahh with 'global', thank you! It never crossed my mind that this should be used in this case. Within functions, 'global' is only required when the global variable is going to be modified. Given that the module won't be changed, why is global required?
 
Regards,
Albert-Jan



More information about the Tutor mailing list