473,799 Members | 3,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

executing list of methods (and collecting results)

Hi all. Im in this situation: I want to perform several kind of
(validating) methods to a given value.
Lets say i have a class named Number, and the following methods:
is_really_a_num ber(),
is_even(),
is_greater_than _zero(),
and so on. All of them returning booleans.

I want the collect_validat ors() method is to execute any of the above
methods, and collect their names as items of a list (wich will be the
collect_validat ors() return value).

My first approach is:

Expand|Select|Wrap|Line Numbers
  1. def collect_validators(self):
  2. v_dict = { 'is_really_a_number': is_really_a_number,
  3. 'is_even': is_even,
  4. 'is_greater_than_zero', is_greater_than_zero
  5. }
  6.  
  7. for name, meth in v_dict.items():
  8. result = meth()
  9. if result: yield name
  10.  
I wondering if is this a good pattern to apply, i like the way it looks
like, at least to me it looks `natural', but...im calling every method
twice here? One in v_dict and again on the dict iteration?

Any suggestion will be great!

Thanks!
Gerardo
Sep 20 '07 #1
5 1407
Gerardo Herzig wrote:
Hi all. Im in this situation: I want to perform several kind of
(validating) methods to a given value.
Lets say i have a class named Number, and the following methods:
is_really_a_num ber(),
is_even(),
is_greater_than _zero(),
and so on. All of them returning booleans.

I want the collect_validat ors() method is to execute any of the above
methods, and collect their names as items of a list (wich will be the
collect_validat ors() return value).

My first approach is:

Expand|Select|Wrap|Line Numbers
  1. def collect_validators(self):
  2.    v_dict = { 'is_really_a_number': is_really_a_number,
  3.                      'is_even': is_even,
  4.                      'is_greater_than_zero', is_greater_than_zero
  5.                   }
  6.       for name, meth in v_dict.items():
  7.          result = meth()
  8.          if result: yield name
  9.  

I wondering if is this a good pattern to apply, i like the way it looks
like, at least to me it looks `natural', but...im calling every method
twice here? One in v_dict and again on the dict iteration?

Any suggestion will be great!

Thanks!
Gerardo
You are not calling every method twice. You are painstakingly typing out
their names twice. But fortunately, functions and methods have a
__name__ attribute which makes a this typing redundant. I would give
your class instances a _validators attribute which is a list of
validating methods, then make the generator like this:

def collect_validat ors(self):
for v in self._validator s:
if v():
yield v.__name__

James
Sep 21 '07 #2
Gerardo Herzig wrote:
I want the collect_validat ors() method is to execute any of the
above methods, and collect their names as items of a list (wich
will be the collect_validat ors() return value).
(inside class definition -- untested)
validators = {"is a number": is_really_a_num ber,
"is even": is_even,
"is greater than zero": is_greater_than _zero}

def collect_validat ors(self):
return [desc for desc, func in self.validators .items() if func()]
My first approach is:
.... no method, but a generator. Executing it will give you a
generator object instead of a result list.
Expand|Select|Wrap|Line Numbers
  1. def collect_validators(self):
  2.     v_dict = { 'is_really_a_number': is_really_a_number,
  3.                       'is_even': is_even,
  4.                       'is_greater_than_zero', is_greater_than_zero
  5.                    }
  6.        for name, meth in v_dict.items():
  7.           result = meth()
  8.           if result: yield name
  9.  

I wondering if is this a good pattern to apply, i like the way it
looks like, at least to me it looks `natural',
IMHO, it doesn't look natural. It depends on what you want to
achieve. This generator will need to be iterated over until it
is "exhausted" .
but...im calling every method twice here?
No. Methods are only called if you apply the function call
operator, "()".

BTW, I hope you don't really want to test a number to be greater
than zero, or even, by using an own method, respectively, just to
test this.

Regards,
Björn

--
BOFH excuse #321:

Scheduled global CPU outage

Sep 21 '07 #3
Gerardo Herzig wrote:
>
>I want the collect_validat ors() method is to execute any of the
above methods, and collect their names as items of a list (wich
will be the collect_validat ors() return value).

(inside class definition -- untested)
validators = {"is a number": is_really_a_num ber,
"is even": is_even,
"is greater than zero": is_greater_than _zero}

def collect_validat ors(self):
return [desc for desc, func in self.validators .items() if func()]
Excelent!!!
>My first approach is:

... no method, but a generator. Executing it will give you a
generator object instead of a result list.
>
Expand|Select|Wrap|Line Numbers
  1. def collect_validators(self):
  2.     v_dict = { 'is_really_a_number': is_really_a_number,
  3.                       'is_even': is_even,
  4.                       'is_greater_than_zero', is_greater_than_zero
  5.                    }
  6.        for name, meth in v_dict.items():
  7.           result = meth()
  8.           if result: yield name

I wondering if is this a good pattern to apply, i like the way it
looks like, at least to me it looks `natural',

IMHO, it doesn't look natural. It depends on what you want to
achieve. This generator will need to be iterated over until it
is "exhausted" .
Im having some fun doing a mail filter. A master thread will fire several
threads (each one returning a list with the matched validators) and
collect the results of each one of them.
>
>but...im calling every method twice here?

No. Methods are only called if you apply the function call
operator, "()".

BTW, I hope you don't really want to test a number to be greater
than zero, or even, by using an own method, respectively, just to
test this.
Haha, no, the actual methods do other kind of things.
Thanks Björn!!!

Cheers.
Gerardo
Sep 21 '07 #4
On Sep 21, 12:26 am, Gerardo Herzig <gher...@fmed.u ba.arwrote:
def collect_validat ors(self):
v_dict = { 'is_really_a_nu mber': is_really_a_num ber,
'is_even': is_even,
'is_greater_tha n_zero', is_greater_than _zero
}

for name, meth in v_dict.items():
result = meth()
if result: yield name
Are these validators actually methods rather than functions? If so,
you should write something like this:

def collect_validat ors(self):
methods = ['is_really_a_nu mber', 'is_even',
'is_greater_tha n_zero']
return (m for m in methods if getattr(self, m)())

--
Paul Hankin

Sep 21 '07 #5
gh*****@fmed.ub a.ar wrote:
Haha, no, the actual methods do other kind of things.
Thanks Björn!!!
Okay, so I hoped. Glad to be of help.

Regards,
Björn

--
BOFH excuse #233:

TCP/IP UDP alarm threshold is set too low.

Sep 21 '07 #6

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

Similar topics

17
1929
by: Istvan Albert | last post by:
Paul McGuire wrote: > Please reconsider the "def f() :" construct. Instead of > invoking a special punctuation character, it uses context and placement, > with familiar old 's, to infuse the declaration of a function with special > characteristics. If this causes def lines to run longer than one line, > perhaps the same rule that allows an unmatched "(" to carry over multiple > lines without requiring "\" continuation markers could be...
14
10465
by: Jay O'Connor | last post by:
Is there a good way to import python files without executing their content? I'm trying some relfection based stuff and I want to be able to import a module dynamically to check it's contents (class ad functions defined) but without having any of the content executed. For example: ---------------------- def test(var): print var
7
5579
by: clr | last post by:
I like to stamp trace logs with the name of the executing Class and Method. I can get the Class Name using GetType.Name and I can get a list of every Method in the class using System.Reflection.MethodInfo objects (code follows) But is there anyway to retrieve the name of the currently executing Method? Or is this a lost cause? (code sample) Dim sClassName as String = Me.GetType.Name Dim aMethod() as System.Reflection.MethodInfo =...
0
2984
by: Mythran | last post by:
I wrote some code that is supposed to enumerate through the specified file's win32 resources and return a string-array of all icon names. When it runs, it returns a string-array with a bunch of numbers in sequential order (1-55 when ran against iexplore.exe). When I open up iexplore.exe in Visual Studio, I see 23 icons. Each icon has 1 or more sizes of the icon...I'm assuming that there are, in fact, 55 icon resources in iexplore.exe,...
6
1678
by: ahart | last post by:
I'm pretty new to python and am trying to write a fairly small application to learn more about the language. I'm noticing some unexpected behavior in using lists in some classes to hold child objects. Here is some abbreviated code to help me explain. #################################### class Item(object) __text = "" def __get_text(self): return self.__text
2
1576
by: Jon Slaughter | last post by:
I was wondering if maybe allowing "fields" for methods. The reason is to encapsulate the data that is mainly used by the method and to prevent the need of having to create new variables every time the function is called if you know they need not change within the method. In a sense these would be equivilent to passing arguments to the method or equivilent to local variables... but these arguments or variables always have the same...
6
1571
by: HMS Surprise | last post by:
Seems to me that one should be able to put the names of several functions in a list and then have the list executed. But it seems the output of the functions is hidden, only their return value is visible. Is this because the list execution is another scope? Thanx, jh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2
1998
by: =?Utf-8?B?Um9nZXIgTWFydGlu?= | last post by:
I am executing an AJAX page method that is a long running task. After starting the first method, I execute a second page method to retrieve the status of the task. It works fine in an empty web application, but when I paste the code into my main application (~10 projects, maybe 100 files) the behavior changes. What happens is the second page method will not begin executing until the first one finishes. In other words, the page methods...
7
909
by: Karlo Lozovina | last post by:
This is what I'm trying to do (create a list using list comprehesion, then insert new element at the beginning of that list): result = .insert(0, 'something') But instead of expected results, I get None as `result`. If instead of calling `insert` method I try to index the list like this: result =
0
9688
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
9546
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
10490
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
10030
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
9078
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
5467
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
5590
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4146
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
2941
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.