I have an object Clock = pygame.time.Clock()
. I want to use it in a module so that whenever I import the module, the module uses the object created in the program. How do I do it?

- 361
- 1
- 6
- 19
-
2A module doesn't "use" anything; a module defines functions and classes (well, at least it *should*). You can pass your clock as an argument to those functions or classes. – Aran-Fey Aug 11 '18 at 09:43
-
Thanks! If you post that as an answer, It will be accepted by me :) - just one doubt - can I pass an object as an argument? – Umesh Konduru Aug 11 '18 at 09:48
-
Everything is an object in python, so naturally you can pass objects as arguments. – Aran-Fey Aug 11 '18 at 09:54
-
That means I can even pass a class instance as an argument, right? – Umesh Konduru Aug 11 '18 at 09:56
-
Yes. You can pass anything you want as an argument. – Aran-Fey Aug 11 '18 at 09:58
-
@UmeshKonduru You usually *only* pass class instances (ie objects). Classes themselves can be passed, but it is used not so often -- usually when you try to process different kinds of objects the same way. – Gnudiff Aug 11 '18 at 09:59
1 Answers
No, you can't, at least not this way.
What you can do is create another module, which defines Clock globally, and import it both into your program and the module. I tried it some time ago, but this is very awkward and leads to all kinds of mistakes.
I tried to do it different ways here Importing variable names into class namespace and Reuse module with different scripts (code organization) , but it was futile.
Normal way is for module functions to have arguments passed to them, that contain the variable you need to setup module. Sometimes it makes sense to organize module into classes because of that -- when you create a class object you set the config/global variables into them.
Like this: module1.py
class funcs_that_use_clock:
def __init__(self,clockconfig):
self.clock=clockconfig
def foo(self):
print self.clock
And yourprogram.py then does:
from module1 import funcs_that_use_clock as F
Clock = pygame.time.Clock()
myfuncs=F(Clock)
myfuncs.foo()
Depending on case, you can have also Class/module-wide variables without need to create actual objects.

- 4,297
- 1
- 24
- 25
-
Well, I'm a beginner at programming and sometimes do not see things that are very simple. As Aran-Fey said in the comments, I can simply pass it as an argument – Umesh Konduru Aug 11 '18 at 09:56
-
@UmeshKonduru No worries. As you can see you are not the only one. The thinking might be different, if you have programmed earlier in languages that only have global namespace also. – Gnudiff Aug 11 '18 at 09:57