How two modules call functions defined in each other?

T

Tian

I am python beginner, I have a question about the interdependence of
modules.

For example, when I have two modules:

module1.py
-------------
def plus(x):
return add(x,1)


module2.py
-------------
def add(x,y):
return x+y

def plus2(x):
return plus(x)+1


How should I write "import" in both files?
What about the global varibals? is there anything like "extern" keyword
in C?
or python has some other solutions?
 
C

Christos TZOTZIOY Georgiou

I am python beginner, I have a question about the interdependence of
modules.
For example, when I have two modules:

module1.py
-------------
def plus(x):
return add(x,1)


module2.py
-------------
def add(x,y):
return x+y

def plus2(x):
return plus(x)+1
How should I write "import" in both files?

In module1, import module2 and vice versa. From moduleX, you access any
attribute (function or "variable") of moduleY by using moduleY.attribute .
What about the global varibals? is there anything like "extern" keyword
in C?

There are no "global variables" in Python, only module-level attributes. If by
global you mean the main program's (which is also a module) attributes, in your
other modules do a:

import __main__

and then access its attributes as __main__.attribute . It's not generally a
good idea in Python, though, so you might like to explain what you need to do so
that we suggest alternate approaches.
or python has some other solutions?

Cheers!
 
R

Reinhold Birkenfeld

Tian said:
I am python beginner, I have a question about the interdependence of
modules.

For example, when I have two modules:

module1.py
-------------
def plus(x):
return add(x,1)


module2.py
-------------
def add(x,y):
return x+y

def plus2(x):
return plus(x)+1


How should I write "import" in both files?
What about the global varibals? is there anything like "extern" keyword
in C?
or python has some other solutions?

Yes. Either define plus and add in module1 or define each one in a
separate module.

Reinhold
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top