Search code examples
pythonpython-3.xmodulergbpython-module

assigning a variable using a separate module?


I have been learning python for a while now, and thought it was about time to learn more about modules. Specifically, how to write them. I have been working through PyGame for a while now, and have grown annoyed with having to define each color that I use. I thought this would be a good place to start with writing a module, but I ran into an error straight away. What I want is something like this, but I don't know how to assign the tuple of rgb to the color in the main script.

Main script:

import rgb_color as rgb
red = rgb.red()

Module:

red():
  (255,0,0)

Solution

  • As noted in the comments, you should probably spend some more time with the basics, such as functions, before heading into modules.

    Still, here you do not need a function, though. A "constant" will do the trick just fine. (Note that there are no true constants in Python, though, just don't modify the values). Just write

    red = (255, 0, 0)
    

    in your module file, or perhaps even better

    RED = (255, 0, 0) # All caps
    

    to better signal that it is supposed to be a constant value.

    Then, when you import your module the constant becomes available. Perhaps it would be a good idea to also look at what __all__ does if you ever think about doing from rgb_color import * even though this is highly discouraged.