473,915 Members | 3,885 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confused about hasattr/getattr/namespaces

I'm confused about the use of hasattr/getattr, or possibly
namespaces. I know how to do this:

class UnderstandThis( object):
def do_foo(self): pass
def do_bar(self): pass
def doit(self, cmd):
funcname = 'do_' + cmd
if hasattr(self, funcname):
getattr(self, funcname)()
else:
print 'not found'

But if I try to do this with classes in a module (instead of
functions in a class):

class FooGenerator(ob ject): ...
class BarGenerator(ob ject): ...

def generate(cmd):
clsname = cmd + 'Generator'
if hasattr(???, clsname):
etc...

I don't know what to use for ??? instead of self. If I print
globals() inside generate() it shows the two classes, but using
it in the hasattr line doesn't work -- huh? I can make it work
by wrapping the generate function in a (otherwise useless) class
and using self -- again, huh?

Couldn't find an explanation or example in the docs. In fact,
the description of vars/globals/locals (in section 2.1) just
confused me even more. Think I'm heading down the wrong path.
Can somebody please un-confuse me?

Brian.
Jul 18 '05 #1
2 2624
On 2004-02-29 13:48:21 -0500, br***@mirror.or g (Brian Roberts) said:
I'm confused about the use of hasattr/getattr, or possibly
namespaces. I know how to do this:

class UnderstandThis( object):
def do_foo(self): pass
def do_bar(self): pass
def doit(self, cmd):
funcname = 'do_' + cmd
if hasattr(self, funcname):
getattr(self, funcname)()
else:
print 'not found'

But if I try to do this with classes in a module (instead of
functions in a class):

class FooGenerator(ob ject): ...
class BarGenerator(ob ject): ...

def generate(cmd):
clsname = cmd + 'Generator'
if hasattr(???, clsname):
etc...

I don't know what to use for ??? instead of self. If I print
globals() inside generate() it shows the two classes, but using
it in the hasattr line doesn't work -- huh? I can make it work
by wrapping the generate function in a (otherwise useless) class
and using self -- again, huh?

Couldn't find an explanation or example in the docs. In fact,
the description of vars/globals/locals (in section 2.1) just
confused me even more. Think I'm heading down the wrong path.
Can somebody please un-confuse me?


if you have the module object, you can use that.. or you could use
sys.modules[__name__] to get the current module (import sys, of course).

globals(), locals() are dictionaries, so you would have to do "clsobj =
globals().get(c lsname)" or something like that. You *probably* want
something more explicit than that though.. it probably wouldn't be too
much work to keep your own command->class dictionary.

-bob

Jul 18 '05 #2
Here's one way:
def generate(cmd):
clsname = cmd + "Generator"
g = globals()
if g.has_key(clsna me): ...
globals() returns the module's dict, not the module. You could also
import modulename as self
but this is a kind of circular import, and the re-use of the name "self"
(which will be used in method definitions) smells bad too.

Jeff

Jul 18 '05 #3

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

Similar topics

2
6989
by: Dragos Chirila | last post by:
Hi I have the following class: class PropTest: def __init__(self): self.prop1 = 1 self._prop2 = 2 self.__prop3 = 3
0
1869
by: Gil Tal | last post by:
Hi, I use urllib2 to download a redirected url and I get an exception from the bowels of urllib2. It seems that urllib2 implements some super sophisticated self check and tries to control the access to attributes using lots of calls to hasattr(the builtin function) and a custom __getattr__() on the Request class that perfroms some checks and raises an AttributeError if it's not happy. The problem is that hasattr() according to the docs is...
2
1437
by: Iyer, Prasad C | last post by:
Actually I am bit confused between the modules and .py file How do I differentiate between the 2. For example I have a file import1.py, import2.py file Which has few functions and classes And if I have a class with same name "BaseClass" in both the file How would I use it if I declare it as given below in my 3rd class
8
4245
by: Øyvind Jægtnes | last post by:
I'm playing around a bit with XPath and nodelist and i want to extract some info from a RSS feed. The one that i am testing at can be viewed at http://slashdot.org/index.rss Ok.. heres the deal: I load xml via httpwebrequest etc and put it in a XmlDocument. xmlFeed.Load(xRes.GetResponseStream()); This works fine as i can use this stream with a XmlReader to parse the
8
1908
by: Steven D'Aprano | last post by:
I came across this unexpected behaviour of getattr for new style classes. Example: >>> class Parrot(object): .... thing = .... >>> getattr(Parrot, "thing") is Parrot.thing True >>> getattr(Parrot, "__dict__") is Parrot.__dict__ False
7
1348
by: Dylan Parry | last post by:
Hi, I've started to get a bit confused by namespaces and hierarchical organisation in general. What I want to do is something like this: Namespace MyNamespace | |- Class Foo | |- Namespace MyNamespace.Foo
1
1280
by: Giulio Petrucci | last post by:
Hi everybody, I'm getting confused about "which-name-give-to-what" developing my applications using Visual Studio. If I have to develop a "Utilities" library containing some classes for logging and other classes used for cryptography shall I build a new Solution named "Utilities"? And how many projects shall I set in it? Let's suppose I need to have two namespaces "Utilities.Log" and "Utilities.Cryptography", in the same assembly......
2
1378
by: Giulio Petrucci | last post by:
Hi everybody, I'm getting confused about "which-name-give-to-what" developing my applications using Visual Studio. If I have to develop a "Utilities" library containing some classes for logging and other classes used for cryptography shall I build a new Solution named "Utilities"? And how many projects shall I set in it? Let's suppose I need to have two namespaces "Utilities.Log" and "Utilities.Cryptography", in the same assembly......
4
3697
by: Emin | last post by:
Dear experts, I got some unexpected behavior in getattr and copy.deepcopy (see transcript below). I'm not sure if this is actually a bug in copy.deepcopy or if I'm doing something too magical with getattr. Comments would be appreciated. Thanks, -Emin
0
9883
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
11359
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
10928
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11069
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10543
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
9734
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...
0
6149
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4779
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
3370
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.