1

So I have two separate Python packages that I'm importing into my Python script for Raspberry Pi. In this case as;

from rflib import*
from Rpi.GPIO import*

However, both packages have their own seperate method cleanup(self)

So, at the end of the script when I use the command cleanup(), how do I a) know which package the method is coming from (they both do utterly different things b) control which one is run?

I've looked into similarly named questions, but which seem to deal with inheritance overloading rather than package imports

Community
  • 1
  • 1
davidhood2
  • 1,367
  • 17
  • 47

2 Answers2

5

from <module> import * takes all names in a module (those that don't start with a _ or everything listed in <module>.__all__ and assigns those names as globals in your current module.

If two modules define the same name, that means that the last one imported this way wins; cleanup = rflib.cleanup is replaced by cleanup = Rpi.GPIO.cleanup with the second from Rpi.GPIO import * statement.

You generally want to avoid using from <module> import *. Import specific names, or just the module itself.

In this case, you can do:

from rflib import cleanup as rflib_cleanup
from Rpi.GPIO import cleanup as rpigpio_cleanup

which would bind those two functions as different names.

Or you could just import the modules:

import rflib
from Rpi import GPIO

which gives you only the rflib and GPIO names, each a reference to the module object, so now you can reference each of the cleanup functions as attributes on those modules:

rflib.cleanup()
GPIO.cleanup()

If you need to use a lot of names from either module, the latter style is preferred because that limits the number of imports you need to do, keeps your namespace clean and un-cluttered, and gives you more context whereever those names are used in your code.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

It is not a good practice to use * with import. You should be doing something like:

import rflib
from Rpi import GPIO

# Clean Up 1
rflib.cleanup

#Clean Up 2
GPIO.cleanup()

Additional pice of information:

In case your files/objects are of same name, in that case you should use as with import. For example:

   from file1 import utils as file1_utils
   from file2 import utils as file2_utils

   file1_utils.my_func()
   file2_utils.my_func()
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126