473,594 Members | 2,996 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 2611
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
6954
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
1852
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
1423
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
4234
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
1896
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
1336
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
1269
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
1367
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
3666
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
7947
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
7880
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
8374
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
8010
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,...
1
5739
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
3868
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...
0
3903
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1486
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1217
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.