473,769 Members | 5,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Are circular dependencies possible in Python?

Like C, Python seems to insist I declare functions before calling
them - rather than, say, scanning to the end of the current script
when it can't immediately find what function I'm referring to.

C lets you predeclare functions to allow for the existence of
functions with circular dependencies.

Does Python allow you to do something similar?

If not how do you create functions with circular dependencies in
Python - where function A could call function B; and function
B could call function A - or is that not possible?
--
__________
|im |yler http://timtyler.org/ ti*@tt1lock.org Remove lock to reply.
Jul 18 '05 #1
8 2054
Tim Tyler wrote:
Like C, Python seems to insist I declare functions before calling
them - rather than, say, scanning to the end of the current script
when it can't immediately find what function I'm referring to.


Yes and no. Yes, they have to exist before you can use them (that only makes
sense), but no, they don't have to be placed in the same order in the source
code like they do with C:
def A(count): .... print 'A', count
.... B(count + 1)
.... def B(count): .... print 'B', count
.... if count < 10:
.... A(count + 1)
.... B(0)

B 0
A 1
B 2
....

See - all that matters is that they exist before you call them.

-Dave
Jul 18 '05 #2
Tim Tyler wrote:
Like C, Python seems to insist I declare functions before calling
them - rather than, say, scanning to the end of the current script
when it can't immediately find what function I'm referring to.

C lets you predeclare functions to allow for the existence of
functions with circular dependencies.

Does Python allow you to do something similar?

If not how do you create functions with circular dependencies in
Python - where function A could call function B; and function
B could call function A - or is that not possible?

Of course, for example:

def A(*args):
if len(args) > 1:
print "Calling B%s" % repr(args[1:])
return B(*args[1:])
else:
print "A Called with: %s" % args[0]

def B(*args):
if len(args) > 1:
print "Calling A%s" % repr(args[1:])
return A(*args[1:])
else:
print "B Called with: %s" % args[0]
A("Arg1","Arg2" ,"Arg3","Arg 4") Calling B('Arg2', 'Arg3', 'Arg4')
Calling A('Arg3', 'Arg4')
Calling B('Arg4',)
B Called with: Arg4


Functions have to exist before you call them, but they are not 'declared'. def
and its enclosed suite is a statement, like print, while, etc... The def
statement is executed to define the function. For functions defined at module
level, this statement is executed when the module is first imported (or
reloaded) in source-code order along with any other module-level code.

Executing a def statement compiles (but does not execute) the body of the
function. Each function, when def'd also gets a reference to the global scope
in which it is defined. When you execute the function body (by calling the
function), identifiers that are not resolved in the functions own local scope
are looked up in this global scope.

So in the example above, the body of A calls B. B is not defined in A's local
scope, so it is looked up in A's globals, which is the module. As long as def
B(... has been executed in the same module before you first call A, everything
is fine.
Michael

Jul 18 '05 #3
On Sat, 9 Apr 2005 15:57:15 GMT,
Tim Tyler <ti*@tt1lock.or g> wrote:
Like C, Python seems to insist I declare functions before calling them
- rather than, say, scanning to the end of the current script when it
can't immediately find what function I'm referring to.
Python has no such restriction.

The only restriction is that the function be defined before it is
called. Unlike C, function definitions in Python are executable
statements.

If your script looks like this:

f( ) # call f

def f( ) # define f
print 'hello'

then it will fail because f has not yet been defined before it was
called.
Does Python allow you to do something similar?
No. Python has no such thing as a function declaration.
If not how do you create functions with circular dependencies in
Python - where function A could call function B; and function
B could call function A - or is that not possible?


Perhaps if you can post a minimal example that shows us what you're
running into, someone here will know how to help.

HTH,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
μ₀ × ε₀ × c² = 1
Jul 18 '05 #4
Tim Tyler <ti*@tt1lock.or g> wrote or quoted:
Like C, Python seems to insist I declare functions before calling
them - rather than, say, scanning to the end of the current script
when it can't immediately find what function I'm referring to.

C lets you predeclare functions to allow for the existence of
functions with circular dependencies.

Does Python allow you to do something similar?

If not how do you create functions with circular dependencies in
Python - where function A could call function B; and function
B could call function A - or is that not possible?


Thanks guys - that's made how Python works in this area abundantly clear.
--
__________
|im |yler http://timtyler.org/ ti*@tt1lock.org Remove lock to reply.
Jul 18 '05 #5
In <IE********@bat h.ac.uk>, Tim Tyler wrote:
Like C, Python seems to insist I declare functions before calling
them - rather than, say, scanning to the end of the current script
when it can't immediately find what function I'm referring to.
They don't have to be declared but to be *defined* in Python before you
can call them. A ``def`` is executed in Python -- a function object is
given a name. The content of a Python script is executed in the order the
code is written.
C lets you predeclare functions to allow for the existence of
functions with circular dependencies.

Does Python allow you to do something similar?


Yes, just define the function before it gets actually called::

def func_a(n):
if n > 5:
return
else:
func_b(n + 1)

def func_b(n):
print n
func_a(n + 1)

func_a(0)

What happens here is

1. Define function A. That function B doesn't exist by now is no problem
because it is not called yet. There's just the instruction to call it if
the body of function A is executed. *Then* function B has to exist.

2. Define function B. You can swap both definitions without problems.

3. Function A is actually called and *must* exist at this point.

Ciao,
Marc 'BlackJack' Rintsch
Jul 18 '05 #6
On Sat, 9 Apr 2005 15:57:15 GMT, Tim Tyler <ti*@tt1lock.or g> wrote:
Like C, Python seems to insist I declare functions before calling
them


One is left wondering what gave you that impression about Python.
Nothing could be further from the truth. The only construct in Python
that smells anything like a declaration is the wartish "global". The
Python philosophy is that everything is dynamic. You don't muck about
with declarations; you just get on with the job. See example below,
where we have a list of functions, which of course all follow the same
protocol, but what that protocol is is of no concern of the Python
compiler.

def nothing_to_decl are(data_fields , validation_func s, other_info):
for k, fld in enumerate(data_ fields):
validation_func s[k](fld, k, other_info)

Aside: How many iterations would it take for the average C programmer
to get the declaration for "validation_fun cs" correct?

Others have pointed out that "def" is executed. So is "class". An OO
example of dynamism would be a bit longer, but would involve creating
classes on the fly and stuffing into them whatever methods are
required for the task at hand.

HTH,

John

Jul 18 '05 #7
Marc 'BlackJack' Rintsch <bj****@gmx.net > wrote or quoted:
In <IE********@bat h.ac.uk>, Tim Tyler wrote:

Like C, Python seems to insist I declare functions before calling
them - rather than, say, scanning to the end of the current script
when it can't immediately find what function I'm referring to.


They don't have to be declared but to be *defined* in Python before you
can call them. [...]


That makes three of you who have called me on my use of "declare".

AFAICT, I was using the standard dictionary definition of this word:

http://dictionary.reference.com/search?q=declare

The term "declare" doesn't have the same meaning as the term "predeclare ".
--
__________
|im |yler http://timtyler.org/ ti*@tt1lock.org Remove lock to reply.
Jul 18 '05 #8
On Sun, 10 Apr 2005 07:34:02 GMT, Tim Tyler <ti*@tt1lock.or g> wrote:
Marc 'BlackJack' Rintsch <bj****@gmx.net > wrote or quoted:
In <IE********@bat h.ac.uk>, Tim Tyler wrote:

> Like C, Python seems to insist I declare functions before calling
> them - rather than, say, scanning to the end of the current script
> when it can't immediately find what function I'm referring to.


They don't have to be declared but to be *defined* in Python before you
can call them. [...]


That makes three of you who have called me on my use of "declare".

AFAICT, I was using the standard dictionary definition of this word:

http://dictionary.reference.com/search?q=declare

The term "declare" doesn't have the same meaning as the term "predeclare ".


We don't need no steenking dictionaries; we're using "declare" and
"define" in the same manner as did K&R:

int foo(int bar); /* declaration */

int foo(int bar) { /* definition */
return 42 * bar;
}

Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
5253
by: jinal jhaveri | last post by:
Hi All, I have one question regarding circular inheritance I have 3 files 1) A.py , having module A and some other modules 2) B.py having module B and some other modules 3) C.py having module C and some other modules
9
5025
by: ajikoe | last post by:
Hello, I have two modules (file1.py and file2.py) Is that ok in python (without any weird implication) if my module import each other. I mean in module file1.py there exist command import file2 and in module file2.py there exist command import file1? This is not working in C#. pujo
1
2098
by: Henry Miller | last post by:
I have the following code (much simplified for this post). Note that SessionKey uses DataAccess, and DataAccess requires SessionKey in it's constructor. Public Class SessionKey Public IsValidSession as Boolean Sub New(UserName, Password) ' Create session, including calls on DataAccess ' to validate username/password
2
3103
by: ernesto basc?n pantoja | last post by:
Hi everybody: I'm implementing a general C++ framework and I have a basic question about circular dependencies: I am creating a base class Object, my Object class has a method defined as: virtual String toString(); where String is defined as:
1
4961
by: Doyle | last post by:
I want middletier objects and data access objects in different namespaces. I want the middle tier object to get a reference to the data access object and pass itself as a parameter to the data access object's constructor, accordingly the constructor of the data access object must declare a datatype of the Middle tier object. The Middle Tier declares a project reference to the Data Access Project to create the Data Access Object.
7
13525
by: barias | last post by:
Although circular dependencies are something developers should normally avoid, unfortunately they are very easy to create accidentally between classes in a VS project (i.e. circular compile-time dependencies). But then I started wondering how "easy" it would be to similarly make a NON-RUNTIME circular dependency between (implicitly linked) DLLs. Indeed authors like John Lakos, who focus on compile/link-time dependencies (not run-time),...
8
4154
by: nyhetsgrupper | last post by:
I have written a windows service and want to expose a web based user interface for this service. I then wrote a class library containing a ..net remoting server. The class library have a method named StartRemotingServer(). To be able to call this method from the windows service I need to reference the remoting class library, but for the class library to be able to access the internal structures of the windows service the class library...
5
3398
by: =?Utf-8?B?Qm9i?= | last post by:
I have a table of dependencies and want to check to see if the dependencies cause a circular reference. Any sugesstions on how to do this using c#. Example, ID DependsOnID 1 2 1 4 2 3 3 1 (circular reference)
6
3472
by: Mosfet | last post by:
Hi, I have two classes, let's call them class A and class B with mutual dependencies as shown below and where implementation is inside .h (no cpp) #include "classB.h" class A {
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10216
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8873
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5309
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.