Re: [Tutor] getattr works sometimes
On Tue, Oct 2, 2012 at 8:39 PM, Steven D'Aprano wrote: > On 03/10/12 04:20, Tino Dai wrote: > >> and the get_class class works sometime for finding modules within a certain directory. If the get_class doesn't work, it throws an AttributeError. >>> >>> I don't really understand what you mean by this. Can you copy and >>> paste the actual error message (all of it)? >>> >>> The module exists in the directory, and I'm trying to debug this. Does anybody have any hints to go about debug this? >>> >>> >> get_class('etl.transfers.bill_**subject') # >> etl.transfers.bill_subject does exist under the transfers directory >> > './leg_apps/etl/transfers/**bill_subject.pyc'> >> > > I don't understand why you are using the get_class function for this. > It is only useful when you don't know the name of the object until > runtime. Since you know the name, I would suggest that using a regular > import is better: > > from etl.transfers import bill_subject > > Imports also work differently to getattr, and I believe that is where > you are running into trouble. The (wrongly named) get_class function > uses getattr to extract names from a single top-level module. But that's > not what you are trying to do: you are trying to extract modules from > a package. > Where I was running into problems was the fact that I needed to import the modules before I could do a getattr using the get_class function. In retrospect, I'm bringing in basically all the objects anyway, so there really is no need to have this complicated set up. > > Use the right tool for the job: you are trying to use a screwdriver when > you need a screwdriver. > > My prediction is that *at some point* in your experiments, you have done > something like: > > etl.transfers.bill_subject = bill_subject > > *or something with the same effect*. Perhaps the "transfers" module > includes one of these lines: > > import bill_subject # Python 2.5 or older? > from . import bill_subject > > > Now bill_subject is an attribute of the transfers module, and getattr can > see it. But you haven't done the same for related_bills, and so getattr > cannot see it. > > Instead, use the right tool, import, which is designed for solving your > problem: > > from etl.transfers import bill_subject > from etl.transfers import related_bills > > should both work, unless you have removed the bill_subject.py and > related_bills.py files from the etl/transfers/ directory. > > Actually Steve, I don't know the correct classes to import until runtime. This is part of a bigger ETL (Extract - Transform - Load) routine, and this is the section that deals with records that didn't make it over because of some missing constraint. You are probably right in the fact that I just should import all the classes in and be done with it. But that brings me to my next question, how do I prevent from polluting the namespace with unneeded imports. Is there a way to de-import modules? Is there an idiom that pertains to this? Thanks, Tino ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr works sometimes
On 03/10/12 04:20, Tino Dai wrote: and the get_class class works sometime for finding modules within a certain directory. If the get_class doesn't work, it throws an AttributeError. I don't really understand what you mean by this. Can you copy and paste the actual error message (all of it)? The module exists in the directory, and I'm trying to debug this. Does anybody have any hints to go about debug this? get_class('etl.transfers.bill_subject') # etl.transfers.bill_subject does exist under the transfers directory I don't understand why you are using the get_class function for this. It is only useful when you don't know the name of the object until runtime. Since you know the name, I would suggest that using a regular import is better: from etl.transfers import bill_subject Imports also work differently to getattr, and I believe that is where you are running into trouble. The (wrongly named) get_class function uses getattr to extract names from a single top-level module. But that's not what you are trying to do: you are trying to extract modules from a package. Use the right tool for the job: you are trying to use a screwdriver when you need a screwdriver. My prediction is that *at some point* in your experiments, you have done something like: etl.transfers.bill_subject = bill_subject *or something with the same effect*. Perhaps the "transfers" module includes one of these lines: import bill_subject # Python 2.5 or older? from . import bill_subject Now bill_subject is an attribute of the transfers module, and getattr can see it. But you haven't done the same for related_bills, and so getattr cannot see it. Instead, use the right tool, import, which is designed for solving your problem: from etl.transfers import bill_subject from etl.transfers import related_bills should both work, unless you have removed the bill_subject.py and related_bills.py files from the etl/transfers/ directory. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr works sometimes
On 03/10/12 03:44, Tino Dai wrote: Hi All, I'm using the get_class from: http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname Do you mean this function? def get_class( kls ): parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__( module ) for comp in parts[1:]: m = getattr(m, comp) return m At only seven lines, it is perfectly acceptable to copy it into your email for the benefit of those who are blocked from accessing the web but still have access to email. Of course it is good to give credit to the original source as well. The name is misleading, because it does not just get classes, it gets any object you like: py> get_class("math.pi") 3.141592653589793 and the get_class class works sometime for finding modules within a certain directory. The get_class function will find modules anywhere that they would be found by the import statement, that is, in the Python module import search path (sys.path). If the get_class doesn't work, it throws an AttributeError. If the module does not exist, or cannot be found, get_class will raise ImportError. If the module is successfully found, but the dotted name does not exist, get_class will raise AttributeError. The module exists in the directory, and I'm trying to debug this. Does anybody have any hints to go about debug this? The usual advise: read the error message, it tells you what went wrong: py> get_class("datetime.datime") Traceback (most recent call last): File "", line 1, in File "", line 6, in get_class AttributeError: 'module' object has no attribute 'datime' I typed the name wrong. It's "datetime", not "datime". py> get_class("datetime.datetime") -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr works sometimes
On 2 October 2012 19:27, Tino Dai wrote: > On Tue, Oct 2, 2012 at 2:20 PM, Tino Dai wrote: and the get_class class works sometime for finding modules within a certain directory. If the get_class doesn't work, it throws an AttributeError. >>> >>> I don't really understand what you mean by this. Can you copy and >>> paste the actual error message (all of it)? >>> The module exists in the directory, and I'm trying to debug this. Does anybody have any hints to go about debug this? >>> >> >> get_class('etl.transfers.bill_subject') # >> etl.transfers.bill_subject does exist under the transfers directory >> > './leg_apps/etl/transfers/bill_subject.pyc'> It shouldn't be returning a module. Is there a class in the bill_subject module that you wanted to get? What happens if you do: get_class('etl.transfers.bill_subject.BillSubject') where BillSubject is the name of the class in the module. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr works sometimes
On Tue, Oct 2, 2012 at 2:20 PM, Tino Dai wrote: >>> and the get_class class works sometime for finding modules within a >>> certain directory. If the get_class >>> doesn't work, it throws an AttributeError. >> >> I don't really understand what you mean by this. Can you copy and >> paste the actual error message (all of it)? >> >>> >>> The module exists in the directory, and I'm trying to debug this. Does >>> anybody have any hints to go about debug >>> this? >> > > get_class('etl.transfers.bill_subject') # > etl.transfers.bill_subject does exist under the transfers directory > './leg_apps/etl/transfers/bill_subject.pyc'> > > get_class('etl.transfers.related_bills')# Also exists under the > transfer directory > ERROR:root:'module' object has no attribute 'related_bills' > Traceback (most recent call last): > File "./leg_apps/etl/transfers/__init__.py", line 63, in get_class > m = getattr(m, comp) > AttributeError: 'module' object has no attribute 'related_bills' > Out[15]: > > That's all I got for the stack trace (logged with exc_info=True) > > -Tino Correction, now neither example is working. :( -T ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr works sometimes
>> and the get_class class works sometime for finding modules within a >> certain directory. If the get_class >> doesn't work, it throws an AttributeError. > > I don't really understand what you mean by this. Can you copy and > paste the actual error message (all of it)? > >> >> The module exists in the directory, and I'm trying to debug this. Does >> anybody have any hints to go about debug >> this? > get_class('etl.transfers.bill_subject') # etl.transfers.bill_subject does exist under the transfers directory get_class('etl.transfers.related_bills')# Also exists under the transfer directory ERROR:root:'module' object has no attribute 'related_bills' Traceback (most recent call last): File "./leg_apps/etl/transfers/__init__.py", line 63, in get_class m = getattr(m, comp) AttributeError: 'module' object has no attribute 'related_bills' Out[15]: That's all I got for the stack trace (logged with exc_info=True) -Tino ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr works sometimes
On 2 October 2012 18:44, Tino Dai wrote: > Hi All, Hi Tino > > I'm using the get_class from: > > http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname Can you show the relevant portion of your code please? > > and the get_class class works sometime for finding modules within a > certain directory. If the get_class > doesn't work, it throws an AttributeError. I don't really understand what you mean by this. Can you copy and paste the actual error message (all of it)? > > The module exists in the directory, and I'm trying to debug this. Does > anybody have any hints to go about debug > this? Not really as you haven't provided enough information. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] getattr works sometimes
Hi All, I'm using the get_class from: http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname and the get_class class works sometime for finding modules within a certain directory. If the get_class doesn't work, it throws an AttributeError. The module exists in the directory, and I'm trying to debug this. Does anybody have any hints to go about debug this? -Tino ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr help
mjole...@gmail.com wrote: > What is the purpose of getattr? Why not just use help or am I completely > misunderstanding this? > >>From what I read, getattr allows you to get a reference to a function >>without knowing its name until runtime. > > However, the example provided is: > > li = ['larry', 'curly] > getattr(li, 'pop') > > It seems to me that I need to know the name of the function to use > getattr? The name need not be known *until* *runtime*. You can pass it as a variable which makes the program more flexible. Here is an example: $ cat getattrdemo.py class Joe: def run(self): print("running") def jump(self): print("jumping") def say_hello(self): print("Hello, I am Joe") class Sue: def say_hello(elf): print("Hello, I am Sue") def swim(self): print("swimming") for person in [Joe(), Sue()]: person.say_hello() actions = [action for action in dir(person) if not action.startswith("_")] print("I can", ", ".join(actions)) while True: action = input("What do you want me to do? ") if action == "": print("bye") break if action in actions: getattr(person, action)() else: print("I'm afraid I can't", action) The code in the for loop does not "know" what joe or sue can do, it detects it at runtime. Therefore you don't have to change it when you add another person (as long as it can .say_hello()). And here's what you may see when you run the script: $ python3 getattrdemo.py Hello, I am Joe I can jump, run, say_hello What do you want me to do? jump jumping What do you want me to do? run running What do you want me to do? swim I'm afraid I can't swim What do you want me to do? bye Hello, I am Sue I can say_hello, swim What do you want me to do? say_hello Hello, I am Sue What do you want me to do? talk I'm afraid I can't talk What do you want me to do? swim swimming What do you want me to do? bye $ If you want to see a more advanced example of the technique, have a look at cmd.py in Python's standard library. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] getattr help
What is the purpose of getattr? Why not just use help or am I completely misunderstanding this? >From what I read, getattr allows you to get a reference to a function without >knowing its name until runtime. However, the example provided is: li = ['larry', 'curly] getattr(li, 'pop') It seems to me that I need to know the name of the function to use getattr? Please help. Sent from my iPhone ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 4:32 PM, Huy Ton That wrote: I have a side question, I am using python 2.7. Why do you use class A: instead of class A(object): ? My example does not depend on old / new style classes. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
class A: def call_by_name(self, func, data): f = A.__dict__.get(func, self.output_text) return f(data) def output_text(self, data):return data def output_hex(self, data):return '\\x' + data a = A() data = 'bar' print a.call_by_name('output_text', data) print a.call_by_name('output_hex', data) print a.call_by_name('foo', data) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
I have a side question, I am using python 2.7. Why do you use class A: instead of class A(object): ? -Huy On Wed, Aug 4, 2010 at 4:08 PM, bob gailer wrote: > On 8/4/2010 4:04 PM, bob gailer wrote: > >> On 8/4/2010 3:44 PM, Huy Ton That wrote: >> >>> Oh, that's right, I should have tried to example in the interpreter >>> instead of in my head:P >>> >>> Say Bob, >>> >>> Is that the preferred method over something like: >>> >> >> I would prefer to create a class and make these functions class methods. >> >> class A: >> def output_text(self, data):return data >> def output_hex(self, data):return '\\x' + data >> def __getattr__(self, name): >>return self.output_text >> a = A() >> data='bar' >> print a.output_text(data) >> print a.output_hex(data) >> print a.foo(data) >> >> I just realized my answer does not accomodate your looking for the > function by name. Please stand by > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 4:04 PM, bob gailer wrote: On 8/4/2010 3:44 PM, Huy Ton That wrote: Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: I would prefer to create a class and make these functions class methods. class A: def output_text(self, data):return data def output_hex(self, data):return '\\x' + data def __getattr__(self, name): return self.output_text a = A() data='bar' print a.output_text(data) print a.output_hex(data) print a.foo(data) I just realized my answer does not accomodate your looking for the function by name. Please stand by -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 3:44 PM, Huy Ton That wrote: Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: I would prefer to create a class and make these functions class methods. class A: def output_text(self, data):return data def output_hex(self, data):return '\\x' + data def __getattr__(self, name): return self.output_text a = A() data='bar' print a.output_text(data) print a.output_hex(data) print a.foo(data) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: >>> import __main__ as main On Wed, Aug 4, 2010 at 3:32 PM, bob gailer wrote: > On 8/4/2010 1:23 PM, Pete wrote: > > Hi, > > I'm trying to understand the syntax for reflection in python. I was > wondering about this. > > From the example on diveintopython: > > http://diveintopython.org/power_of_introspection/index.html > > import statsout > def output(data, format="text"): > output_function = getattr(statsout, "output_%s" % format, > statsout.output_text) > return output_function(data) > >I was wondering about how to make this work if the function that you > are trying to call is not in a module. > > > Everything in Python is in a module. I suspect you mean not in an imported > module, e.g. in the main module. Whose __name__ is '__main__'. A reference > to the main module can be found: > > import sys > main = sys.modules['__main__'] > > Is that possible? > > Something like this: > > def output_text(data): > > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(*, "output_%s" % format, > statsout.output_text) > return output_function(data) > > > What I can't figure out is what to put in place of *. I've tried > globals()['__name__'], in various forms, to no avail. > > > Replace those stars with main as derived above. > > globals()['output_text'] will also give you a reference to the function. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
On 8/4/2010 1:23 PM, Pete wrote: Hi, I'm trying to understand the syntax for reflection in python. I was wondering about this. From the example on diveintopython: http://diveintopython.org/power_of_introspection/index.html import statsout def output(data, format="text"): output_function = getattr(statsout,"output_%s" % format, statsout.output_text) return output_function(data) I was wondering about how to make this work if the function that you are trying to call is not in a module. Everything in Python is in a module. I suspect you mean not in an imported module, e.g. in the main module. Whose __name__ is '__main__'. A reference to the main module can be found: import sys main = sys.modules['__main__'] Is that possible? Something like this: def output_text(data): return_value = "This is text: " + data return return_value def output(data, format="text"): output_function = getattr(*,"output_%s" % format, statsout.output_text) return output_function(data) What I can't figure out is what to put in place of *. I've tried globals()['__name__'], in various forms, to no avail. Replace those stars with main as derived above. globals()['output_text'] will also give you a reference to the function. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
*You can do like below Pete. Where globals has a reference to all functions in this space.* def output(data, format="text"): output_function = getattr(globals()['FUNCTION'], "output_%s" % format, statsout.output_text) return output_function(data) On Wed, Aug 4, 2010 at 3:18 PM, Pete wrote: > Hey Huy, > > thanks. But what is the first parameter in this case? (Note there is > nothing here I'm trying to accomplish except understand). > > In the original example, 'statsout' is the name of the module. In this case > there is no module so why can you substitute 'output_text'? > > thanks, > > Pete > > On 2010-08-04, at 3:09 PM, Huy Ton That wrote: > > If it is in the same code, and the namespace isn't a module or another > class you could do this: > > def output_text(data): > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(output_text, "output_%s" % format, > output_text) > return output_function(data) > > -HTH > > Huy > > On Wed, Aug 4, 2010 at 1:23 PM, Pete wrote: > >> Hi, >> >> I'm trying to understand the syntax for reflection in python. I was >> wondering about this. >> >> From the example on diveintopython: >> >>http://diveintopython.org/power_of_introspection/index.html >> >> import statsout >> def output(data, format="text"): >> output_function = getattr(statsout, "output_%s" % format, >> statsout.output_text) >> return output_function(data) >> >> >> I was wondering about how to make this work if the function that you are >> trying to call is not in a module. Is that possible? >> >> Something like this: >> >> def output_text(data): >> >> >> return_value = "This is text: " + data >> return return_value >> >> >> def output(data, format="text"): >> output_function = getattr(*, "output_%s" % format, >> statsout.output_text) >> return output_function(data) >> >> >> What I can't figure out is what to put in place of *. I've tried >> globals()['__name__'], in various forms, to no avail. >> >> Any pointers would be appreciated. >> >> thanks, >> >> Pete >> >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
Hey Huy, thanks. But what is the first parameter in this case? (Note there is nothing here I'm trying to accomplish except understand). In the original example, 'statsout' is the name of the module. In this case there is no module so why can you substitute 'output_text'? thanks, Pete On 2010-08-04, at 3:09 PM, Huy Ton That wrote: > If it is in the same code, and the namespace isn't a module or another class > you could do this: > > def output_text(data): > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(output_text, "output_%s" % format, output_text) > return output_function(data) > > -HTH > > Huy > > On Wed, Aug 4, 2010 at 1:23 PM, Pete wrote: > Hi, > > I'm trying to understand the syntax for reflection in python. I was wondering > about this. > > From the example on diveintopython: > >http://diveintopython.org/power_of_introspection/index.html > > > import statsout > > def output(data, format="text"): > output_function = getattr(statsout, "output_%s" % format, > statsout.output_text) > return output_function(data) > > > I was wondering about how to make this work if the function that you are > trying to call is not in a module. Is that possible? > > Something like this: > > > def output_text(data): > > return_value = "This is text: " + data > return return_value > > > > def output(data, format="text"): > output_function = getattr(*, "output_%s" % format, > statsout.output_text) > return output_function(data) > > What I can't figure out is what to put in place of *. I've tried > globals()['__name__'], in various forms, to no avail. > > Any pointers would be appreciated. > > thanks, > > Pete > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] getattr()
Hi, I'm trying to understand the syntax for reflection in python. I was wondering about this. From the example on diveintopython: http://diveintopython.org/power_of_introspection/index.html import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" % format, statsout.output_text) return output_function(data) I was wondering about how to make this work if the function that you are trying to call is not in a module. Is that possible? Something like this: def output_text(data): return_value = "This is text: " + data return return_value def output(data, format="text"): output_function = getattr(*, "output_%s" % format, statsout.output_text) return output_function(data) What I can't figure out is what to put in place of *. I've tried globals()['__name__'], in various forms, to no avail. Any pointers would be appreciated. thanks, Pete ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
Janos, I'm confused... # #This should be the complete file def OnMenuFindMe(): print 'You found me' f = getattr(What_Should_It_Be???, 'OnMenuFindMe') f() # You are trying to get a reference to a function in the same file and whose name you know? So why not just f = OnMenuFindMe f() Or just call the function! getattr makes sense when its another module or a class where you may not have access to the function somehow but it doesn't make much sense in this case - at least not to me! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
Tony Cappellini wrote: > From: Kent Johnson <[EMAIL PROTECTED]> > > >>> or you can import __main__, which is the top-level module > Do you mean __main__ is the top level module for every python > program/script? > Yes, at least in the standard Python runtime, I'm not sure what happens when running in IDLE, for example. > Where did you read about this? Not sure, but this is what makes the test for __name__ == '__main__' work, and importing __main__ comes up occasionally on comp.lang.python. Also see http://docs.python.org/ref/naming.html#l2h-320 Kent PS Please reply on list. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] getattr()
Dear Kent, >>You can look up the function in the globals() dict, or you can import >>__main__, which is the top-level module, and use getattr() on it. Or you >>could wrap your functions in a class... >> >>def OnMenuFindMe(): >> print 'You found me' >> >>f = globals()['OnMenuFindMe'] >> >>f() >> >>import __main__ >> >>g = getattr(__main__, 'OnMenuFindMe') >>g() >> >>Kent Many thanks. Yours sincerely, __ János Juhász ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr()
János Juhász wrote: > > Dear All, > > I want to use getattr() to collect a list with all the functions on my > simple script those has got some functionname like 'On'. > > #This should be the complete file > def OnMenuFindMe(): > print 'You found me' > > f = getattr(What_Should_It_Be???, 'OnMenuFindMe') > > f() > #Till here > > It can use getattr() to get an object of a class or module, but not in > this much simpler situation. You can look up the function in the globals() dict, or you can import __main__, which is the top-level module, and use getattr() on it. Or you could wrap your functions in a class... def OnMenuFindMe(): print 'You found me' f = globals()['OnMenuFindMe'] f() import __main__ g = getattr(__main__, 'OnMenuFindMe') g() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] getattr()
Dear All, I want to use getattr() to collect a list with all the functions on my simple script those has got some functionname like 'On'. #This should be the complete file def OnMenuFindMe(): print 'You found me' f = getattr(What_Should_It_Be???, 'OnMenuFindMe') f() #Till here It can use getattr() to get an object of a class or module, but not in this much simpler situation. Yours sincerely, __ János Juhász ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr of functions
Negroup - wrote: > Hi all! I'm here again with a question about introspection. > > My module stores a set of functions. I need to know, from another > script, if a particular function of this module "is enabled" (it > means, if it shall be executed by the caller script). I looked for > some introspective builtin/function, but I didn't find anything useful > (except func_globals, func_dict, func_code, etc, that don't help in my > case). > > This is my solution: > > mymodule.py > def f1(): > pass > def f2(): > pass > > setattr(f1, 'enabled', True) > setattr(f2, 'enabled', False) This seems OK to me. You don't need setattr(), you can set the attribute directly: f1.enabled = True Adding attributes to functions is only supported in recent versions of Python so this is not a good solution if you need to work with older versions. >From your later description I see that you want to do this dynamically and the >set of enabled functions is really a property of the client, not of the >function itself. You have a list of headers and you want to apply all the >functions that match the headers. I would look for a way to have the client >figure out which functions to apply. Maybe keep a list of the headers and use >it to filter the list of functions. For example if fns is the list of functions and headers is a list (or set) of header names matching the functions you could do for fn in fns: if fn.__name__ in headers: fn() This keeps the responsibility for executing the correct functions with the client which seems like the right place to me. Also if it matters, your solution is not thread-safe because it uses global state (the enabled flag in the function). If you have multiple threads doing this you will get errors. Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr of functions
2005/11/24, Liam Clarke <[EMAIL PROTECTED]>: > What do you mean enabled? > > If it's imported into the namespace you can call it... > > Err, can you clarify on the enabling, what context are you using it > in, and what are you trying to achieve? Hi, sorry. I'll try to present the actors omitting the details. table.txt: the first line is an header that lists all the table's fields. Following lines represent data; skel.py: it is script that get headers in table.txt and write the module mymodule.py; mymodule.py: it is a skeleton where are defined a number of functions. This number depends on the number of headers, and it may vary (different table.txt files have a different number of headers, which a different name too). Each function in the module has the name of an header. Finally there is another script, modifiers.py: it imports all the functions in mymodule and applies these functions to the corresponding fields. AS I don't want to apply all these functions indistinctly, I need a way to mark a function like enabled or disabled. If it is enabled, it will be invoked. It it results disabled, it won't be called (and thus, the corresponding field won't be modified). I don't know if it makes sense to you, I should explain better the whole flow.. However I don't think it is the right place. Anyway, I hope the scenario is a bit more free from clouds! Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getattr of functions
What do you mean enabled? If it's imported into the namespace you can call it... Err, can you clarify on the enabling, what context are you using it in, and what are you trying to achieve? On 11/25/05, Negroup - <[EMAIL PROTECTED]> wrote: > Hi all! I'm here again with a question about introspection. > > My module stores a set of functions. I need to know, from another > script, if a particular function of this module "is enabled" (it > means, if it shall be executed by the caller script). I looked for > some introspective builtin/function, but I didn't find anything useful > (except func_globals, func_dict, func_code, etc, that don't help in my > case). > > This is my solution: > > mymodule.py > def f1(): > pass > def f2(): > pass > > setattr(f1, 'enabled', True) > setattr(f2, 'enabled', False) > > [EMAIL PROTECTED]:~/projects/erp/migra$ python > Python 2.3.5 (#1, Sep 6 2005, 12:53:27) > [GCC 3.3.4] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> from mymodule import * > >>> f1.enabled > False > >>> f2.enabled > True > > This seems to work.. I wonder for better solutions. > > Thanks you all! > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] getattr of functions
Hi all! I'm here again with a question about introspection. My module stores a set of functions. I need to know, from another script, if a particular function of this module "is enabled" (it means, if it shall be executed by the caller script). I looked for some introspective builtin/function, but I didn't find anything useful (except func_globals, func_dict, func_code, etc, that don't help in my case). This is my solution: mymodule.py def f1(): pass def f2(): pass setattr(f1, 'enabled', True) setattr(f2, 'enabled', False) [EMAIL PROTECTED]:~/projects/erp/migra$ python Python 2.3.5 (#1, Sep 6 2005, 12:53:27) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from mymodule import * >>> f1.enabled False >>> f2.enabled True This seems to work.. I wonder for better solutions. Thanks you all! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor