473,407 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

A scoping question

This must be another newbie gotchas.

Consider the following silly code, let say I have the following in file1.py:

#=============
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=============

and in file2.py, I have:

#=============
global myBaseClass
class BaseClass:
def __init__(self):
self.MyChilds = []
...
def AddChild(NewChild):
self.MyChilds.append(NewChild)
...
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds: # <- ERROR
...
#=============

When I run this, Python complains that myBaseClass is undefined in the last
line above.

What am I doing wrong? (Yes, I know I am thinking too much in C). I
thought the global declaration would have been sufficient but it's obviously
not.

Thanks,
Jul 18 '05 #1
8 1421
On Tue, 28 Dec 2004 19:34:36 GMT, It's me <it***@yahoo.com> wrote:
This must be another newbie gotchas.

Consider the following silly code, let say I have the following in file1.py:

#=============
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=============
You have declared myBaseClass to be global, but it doesn't exist.

Consider the following code:

global name
print name.__len__()

This will return a NamError

However, the following code will run just fine:

global name
name = "python"
print name.__len__()

will return 6

and in file2.py, I have:

#=============
global myBaseClass
class BaseClass:
def __init__(self):
self.MyChilds = []
...
def AddChild(NewChild):
self.MyChilds.append(NewChild)
...
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds: # <- ERROR
...
#=============

When I run this, Python complains that myBaseClass is undefined in the last
line above.

What am I doing wrong? (Yes, I know I am thinking too much in C). I
thought the global declaration would have been sufficient but it's obviously
not.

Thanks,

--
http://mail.python.org/mailman/listinfo/python-list


HTH

--
Premshree Pillai
http://www.livejournal.com/~premshree
Jul 18 '05 #2

"Premshree Pillai" <pr**************@gmail.com> wrote in message
news:ma**************************************@pyth on.org...
On Tue, 28 Dec 2004 19:34:36 GMT, It's me <it***@yahoo.com> wrote:
This must be another newbie gotchas.

Consider the following silly code, let say I have the following in file1.py:
#=============
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=============


You have declared myBaseClass to be global, but it doesn't exist.


No, myBaseClass exists in file1.py. The question is how can I tell
file2.py that the global variable is in file1 (without doing a silly
file1.myBaseClass....

Since I am invoking file2 from file1, I would have thought that global
variables in file1 exists automatically....(too much C thinking, I know)
Jul 18 '05 #3
On Tue, 28 Dec 2004 19:59:01 GMT, It's me <it***@yahoo.com> wrote:

"Premshree Pillai" <pr**************@gmail.com> wrote in message
news:ma**************************************@pyth on.org...
On Tue, 28 Dec 2004 19:34:36 GMT, It's me <it***@yahoo.com> wrote:
This must be another newbie gotchas.

Consider the following silly code, let say I have the following in file1.py:
#=============
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=============
You have declared myBaseClass to be global, but it doesn't exist.


No, myBaseClass exists in file1.py. The question is how can I tell


Umm, from the sample code (for file2.py) that you provided, I don't
see myBaseClass. You've only declared it to be global in file2.py, but
it does not exist -- does not exist in the sense that it has no type
associated with it, which in turn means meaning you cannot apply
methods to it.
file2.py that the global variable is in file1 (without doing a silly
file1.myBaseClass....

Since I am invoking file2 from file1, I would have thought that global
variables in file1 exists automatically....(too much C thinking, I know)
--
http://mail.python.org/mailman/listinfo/python-list

--
Premshree Pillai
http://www.livejournal.com/~premshree
Jul 18 '05 #4
It's me wrote:
This must be another newbie gotchas.

Consider the following silly code, let say I have the following in file1.py:

#=============
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=============

and in file2.py, I have:

#=============
global myBaseClass
class BaseClass:
def __init__(self):
self.MyChilds = []
...
def AddChild(NewChild):
self.MyChilds.append(NewChild)
...
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds: # <- ERROR
...
#=============

When I run this, Python complains that myBaseClass is undefined in the last
line above.

What am I doing wrong? (Yes, I know I am thinking too much in C). I
thought the global declaration would have been sufficient but it's obviously
not.


I think you're confused about what the global keword does. Declaring a
name as global makes that name global *to the module*:

http://docs.python.org/ref/global.html
http://docs.python.org/lib/built-in-funcs.html#l2h-32

What you probably want instead is:

-------------------- file1.py --------------------
import file2
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
--------------------------------------------------

-------------------- file2.py --------------------
class BaseClass:
def __init__(self):
self.MyChilds = []
def AddChild(self, NewChild):
self.MyChilds.append(NewChild)
class NextClass:
def __init__(self):
from file1 import myBaseClass # IMPORT
for eachChild in myBaseClass.MyChilds:
pass
--------------------------------------------------

Note that I import myBaseClass in __init__. If I imported it at the top
of the module, then file1 would import file2 which would then import
file1 and you'd have a circular dependency.

As it is, your code is very tightly coupled. Why don't you put all this
code into a single module?

Steve
Jul 18 '05 #5
It's me wrote:
This must be another newbie gotchas.

Consider the following silly code

[snip tightly coupled code]

A few options that also might work better than such tightly coupled modules:

-------------------- file1.py --------------------
import file2
myBaseClass = file2.BaseClass()
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds:
pass
myBaseClass.AddChild(file2.NextClass())
--------------------------------------------------

-------------------- file2.py --------------------
class BaseClass:
def __init__(self):
self.MyChilds = []
def AddChild(self, NewChild):
self.MyChilds.append(NewChild)
--------------------------------------------------
or
-------------------- file1.py --------------------
import file2
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass(myBaseClass))
--------------------------------------------------

-------------------- file2.py --------------------
class BaseClass:
def __init__(self):
self.MyChilds = []
def AddChild(self, NewChild):
self.MyChilds.append(NewChild)
class NextClass:
def __init__(self, myBaseClass):
for eachChild in myBaseClass.MyChilds:
pass
--------------------------------------------------
Jul 18 '05 #6
Thanks, Steve.

So, global is only to within a module (I was afraid of that). Those words
flashed by me when I was reading it but since the word "module" didn't
translate to "file" in my C mind, I didn't catch that.

In that case, you are correct that I have to do an import of file1 in file2.

Not that this is not real code, I am still trying to learn the ins and outs
of Python by writing some silly code - but will be important to help me
understand how I would write the real code.

Regarding the question of not placing everything in one module, I wouldn't
think that that's how I would do it. I might get ambitous later and write
code for a larger project. In that case, I will need to know more about
scoping across multiple modules. So, this helps me understand what to do.

Thanks again.

"Steven Bethard" <st************@gmail.com> wrote in message
news:I5jAd.246742$5K2.73425@attbi_s03...

<snip>

I think you're confused about what the global keword does. Declaring a
name as global makes that name global *to the module*:

http://docs.python.org/ref/global.html
http://docs.python.org/lib/built-in-funcs.html#l2h-32

What you probably want instead is:

-------------------- file1.py --------------------
import file2
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
--------------------------------------------------

-------------------- file2.py --------------------
class BaseClass:
def __init__(self):
self.MyChilds = []
def AddChild(self, NewChild):
self.MyChilds.append(NewChild)
class NextClass:
def __init__(self):
from file1 import myBaseClass # IMPORT
for eachChild in myBaseClass.MyChilds:
pass
--------------------------------------------------

Note that I import myBaseClass in __init__. If I imported it at the top
of the module, then file1 would import file2 which would then import
file1 and you'd have a circular dependency.

As it is, your code is very tightly coupled. Why don't you put all this
code into a single module?

Steve

Jul 18 '05 #7
It's me wrote:
#=============
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#============= [snip] #=============
global myBaseClass
class BaseClass:
def __init__(self):
self.MyChilds = []
...
def AddChild(NewChild):
self.MyChilds.append(NewChild)
...
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds: # <- ERROR
...
#=============


Also worth mentioning if you're just starting with Python. Python has
some official naming conventions:

http://www.python.org/peps/pep-0008.html

These are just recommendations of course, but if you have the option
(e.g. you're not constrained by style enforced by your employer), and
you'd like your code to look more like standard Python modules, you
might consider using these suggestions. This would make your code look
something like:

#=============
import file2
global my_base_class
my_base_class = file2.BaseClass()
my_base_class.add_child(file2.NextClass())
#=============

#=============
global my_base_class
class BaseClass:
def __init__(self):
self.my_childs = []
...
def add_child(new_child):
self.my_childs.append(new_child)
...
class NextClass:
def __init__(self):
for each_child in my_base_class.my_childs: # <- ERROR
...
#=============

Steve
Jul 18 '05 #8
On Tue, 28 Dec 2004 19:34:36 GMT, "It's me" <it***@yahoo.com> declaimed
the following in comp.lang.python:
This must be another newbie gotchas.

Consider the following silly code, let say I have the following in file1.py:

#=============
import file2
global myBaseClass
#1 "global" only applies within a function definition,
where it signals that the subsequent name will be modified within the
function AND exists in the scope external to the function... If the
object name ONLY appears on the right side of an assignment (within the
function), "global" is not needed, as the scope rules will look-up the
external item. However, if the object name appears on the left hand
side, and there is NO "global", Python creates a local object (and will
then complain if you used the name on a right-side before the assignment
creating it).

aGlobalItem = [1, 2, 3]

def aFunction():
global aGlobalItem
aGlobalItem = ('a', 'b', 'c')
return None

Without the "global", the function would create a function-local
called aGlobalItem, and never see the outside object.
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=============

and in file2.py, I have:

#=============
global myBaseClass
class BaseClass:
def __init__(self):
self.MyChilds = []
...
def AddChild(NewChild):
self.MyChilds.append(NewChild)
...
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds: # <- ERROR
...
#=============

When I run this, Python complains that myBaseClass is undefined in the last
line above.
Which is correct. "global" only works within function
definitions /within/ a module (file). To access stuff in other modules
you must "import" the module.
What am I doing wrong? (Yes, I know I am thinking too much in C). I
thought the global declaration would have been sufficient but it's obviously
not.
#2 You are trying to create a set of recursive
dependencies. File1 is getting an object definition from File2, but
File2 needs the object created in File1...

Terrible design, IMHO...
And why is NextClass a "class"? Does it return a "NextClass"
object?

Either way... I'd probably change the __init__ to take two
arguments: self (which is the NextClass object being created) and 'o'
(the other argument), then use it as

nc = NextClass(myBaseClass)

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #9

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

Similar topics

2
by: David Stockwell | last post by:
Hi, Another of my crazy questions. I'm just in the process of learning so bear with me if you can. I actually ran it.... with two test cases TEST CASE 1: Say I have the following defined:...
4
by: Frederick Grim | last post by:
okay so the code in question looks like: namespace util { template<typename C> inline void mmapw(C *& ptr, size_t length, int prot, int flags, int fd, off_t offset) { if((ptr =...
4
by: Joel Gordon | last post by:
Hi, When I try and compile the a class containing the following method : public void doSomething() { for (int i=0; i<5; i++) { IList list = new ArrayList(); Console.WriteLine( i /...
4
by: Sohum | last post by:
Hi I'm reasonably new to this group, and to programming in general. I'd like to know, can you selectively scope within an interface? For example: Public Interface MyInterface Friend...
9
by: NevilleDNZ | last post by:
Can anyone explain why "begin B: 123" prints, but 456 doesn't? $ /usr/bin/python2.3 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13,...
3
by: morris.slutsky | last post by:
So every now and then I like to mess around with hobby projects - I often end up trying to write an OpenGL video game. My last attempt aborted due to the difficulty of automating game elements and...
17
by: Chad | last post by:
The following question stems from Static vs Dynamic scoping article in wikipedia. http://en.wikipedia.org/wiki/Scope_(programming)#Static_versus_dynamic_scoping Using this sites example, if I...
3
by: SPECTACULAR | last post by:
Hi all. I have a question here.. what kind of scoping does C++ use? and what kind does Smalltalk use? I know smalltalk is a little bit old .. but any help would be appreciated.
1
by: jholg | last post by:
Hi, regarding automatically adding functionality to a class (basically taken from the cookbook recipee) and Python's lexical nested scoping I have a question wrt this code: #-----------------...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
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,...

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.