How to detect an undefined method?

2022-03-27 Thread Manfred Lotz
Let's say I have a Python app and have used an undefined method somewhere. Let
us further assume I have not detected it thru my tests.

Is there a way to detect it before deploying the app? pylint doesn't notice it.


Minimal example:

#!/usr/bin/env python3

import logging
from logging import Logger
from random import randrange

def main():
"""
Below logger.err gives

'Logger' object has no attribute 'err'
"""

logger = logging.getLogger('sample')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
logger.addHandler(handler)

num = randrange(0,1000)
if num == 0:
logger.err("got zero")
else:
logger.info(f'got a positive integer: {num}')

if __name__ == "__main__":
main()



-- 
Manfred
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to detect an undefined method?

2022-03-27 Thread dn
On 27/03/2022 22.24, Manfred Lotz wrote:
> Let's say I have a Python app and have used an undefined method somewhere. Let
> us further assume I have not detected it thru my tests.
> 
> Is there a way to detect it before deploying the app? pylint doesn't notice 
> it.


A competent IDE will 'find' such a fault, eg PyCharm indicates the usage
of an identifier for which it can't find a definition, by displaying a
wavy/colored line beneath it - but it won't complain or stop us from
running such code!


Similarly, the interpreter will not object to running the code, until
that line, that branch of logic, is actually executed!


The answer may be to improve the testing regime, to ensure that the
tests cover every line of logic in the code. Much of the time this is a
reasonable target. Sometimes it is too 'expensive'.

The following article includes both pros and cons of using coverage.py:

How to use code coverage in Python with pytest?
April 11, 2021 Sebastian python, testing software   
Basics
What is code coverage?
In the simplest words, code coverage is a measure of exhaustiveness of a
test suite. 100% code coverage means that a system is fully tested.
...
https://breadcrumbscollector.tech/how-to-use-code-coverage-in-python-with-pytest/
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to detect an undefined method?

2022-03-27 Thread Peter Otten

On 27/03/2022 11:24, Manfred Lotz wrote:

Let's say I have a Python app and have used an undefined method somewhere. Let
us further assume I have not detected it thru my tests.

Is there a way to detect it before deploying the app? pylint doesn't notice it.


Minimal example:

#!/usr/bin/env python3

import logging
from logging import Logger
from random import randrange

def main():
 """
 Below logger.err gives

 'Logger' object has no attribute 'err'
 """

 logger = logging.getLogger('sample')
 logger.setLevel(logging.DEBUG)
 handler = logging.StreamHandler()
 logger.addHandler(handler)

 num = randrange(0,1000)
 if num == 0:
 logger.err("got zero")
 else:
 logger.info(f'got a positive integer: {num}')

if __name__ == "__main__":
 main()


mypy --strict will find that one. Be warned though that this is a
slippery slope: you may end up fixing quite a few non-errors...

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


Re: How to detect an undefined method?

2022-03-27 Thread Skip Montanaro
> Let's say I have a Python app and have used an undefined method somewhere.
> Let
> us further assume I have not detected it thru my tests.
>
> Is there a way to detect it before deploying the app? pylint doesn't
> notice it.
>

This is maybe not exactly what you're looking for, but writing a test to
exercise that function call (if possible) would be top of my list. Next on
my list would be to use coverage to get a good idea of what code is not
tested. Writing more test cases to reduce the number of uncovered lines
will also make it easier to manually examine the rest of your (untested) code
to find calls to missing functions or methods.

Skip

>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to detect an undefined method?

2022-03-27 Thread Kirill Ratkin via Python-list

Hi

You can get all methods of your object and check the method you want to 
call is there or not.


|methods = [method for method in dir() if 
callable(getattr(, method))] if 'method_you_need' in 
methods: . // BR |


27.03.2022 12:24, Manfred Lotz пишет:

Let's say I have a Python app and have used an undefined method somewhere. Let
us further assume I have not detected it thru my tests.

Is there a way to detect it before deploying the app? pylint doesn't notice it.


Minimal example:

#!/usr/bin/env python3

import logging
from logging import Logger
from random import randrange

def main():
 """
 Below logger.err gives

 'Logger' object has no attribute 'err'
 """

 logger = logging.getLogger('sample')
 logger.setLevel(logging.DEBUG)
 handler = logging.StreamHandler()
 logger.addHandler(handler)

 num = randrange(0,1000)
 if num == 0:
 logger.err("got zero")
 else:
 logger.info(f'got a positive integer: {num}')

if __name__ == "__main__":
 main()




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


Re: How to detect an undefined method?

2022-03-27 Thread Manfred Lotz
On 3/27/22 18:36, Skip Montanaro wrote:
>> Let's say I have a Python app and have used an undefined method somewhere.
>> Let
>> us further assume I have not detected it thru my tests.
>>
>> Is there a way to detect it before deploying the app? pylint doesn't
>> notice it.
>>
> 
> This is maybe not exactly what you're looking for, but writing a test to
> exercise that function call (if possible) would be top of my list. Next on
> my list would be to use coverage to get a good idea of what code is not
> tested. Writing more test cases to reduce the number of uncovered lines
> will also make it easier to manually examine the rest of your (untested) code
> to find calls to missing functions or methods.
> 

If the code base is large it might be difficult to have a test case for all
things. But I agree that coverage is surely a good thing to use.


-- 
Manfred

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


Re: How to detect an undefined method?

2022-03-27 Thread Manfred Lotz
On 3/27/22 18:12, Peter Otten wrote:
> On 27/03/2022 11:24, Manfred Lotz wrote:
>> Let's say I have a Python app and have used an undefined method somewhere. 
>> Let
>> us further assume I have not detected it thru my tests.
>>
>> Is there a way to detect it before deploying the app? pylint doesn't notice 
>> it.
>>
>>
>> Minimal example:
>>
>> #!/usr/bin/env python3
>>
>> import logging
>> from logging import Logger
>> from random import randrange
>>
>> def main():
>>  """
>>  Below logger.err gives
>>
>>  'Logger' object has no attribute 'err'
>>  """
>>
>>  logger = logging.getLogger('sample')
>>  logger.setLevel(logging.DEBUG)
>>  handler = logging.StreamHandler()
>>  logger.addHandler(handler)
>>
>>  num = randrange(0,1000)
>>  if num == 0:
>>  logger.err("got zero")
>>  else:
>>  logger.info(f'got a positive integer: {num}')
>>
>> if __name__ == "__main__":
>>  main()
> 
> mypy --strict will find that one. Be warned though that this is a
> slippery slope: you may end up fixing quite a few non-errors...
> 

Great. I wasn't aware of --strict. Regarding 'slippery slope': I anyway would
only fix what I believe is an error.


Thanks.

-- 
Manfred
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to detect an undefined method?

2022-03-27 Thread Manfred Lotz
On 3/27/22 18:57, Kirill Ratkin wrote:
> Hi
> 
> You can get all methods of your object and check the method you want to call 
> is
> there or not.
> 
> |methods = [method for method in dir() if
> callable(getattr(, method))] if 'method_you_need' in methods:
> . // BR |
> 

I don't understand how this may help. Assume somebody has a codebase of 15T
lines of Python code. How do you want to apply your method?

But perhaps I overlook things.

-- 
Manfred


> 27.03.2022 12:24, Manfred Lotz пишет:
>> Let's say I have a Python app and have used an undefined method somewhere. 
>> Let
>> us further assume I have not detected it thru my tests.
>>
>> Is there a way to detect it before deploying the app? pylint doesn't notice 
>> it.
>>
>>
>> Minimal example:
>>
>> #!/usr/bin/env python3
>>
>> import logging
>> from logging import Logger
>> from random import randrange
>>
>> def main():
>>  """
>>  Below logger.err gives
>>
>>  'Logger' object has no attribute 'err'
>>  """
>>
>>  logger = logging.getLogger('sample')
>>  logger.setLevel(logging.DEBUG)
>>  handler = logging.StreamHandler()
>>  logger.addHandler(handler)
>>
>>  num = randrange(0,1000)
>>  if num == 0:
>>  logger.err("got zero")
>>  else:
>>  logger.info(f'got a positive integer: {num}')
>>
>> if __name__ == "__main__":
>>  main()
>>
>>
>>

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


Re: How to detect an undefined method?

2022-03-27 Thread Kirill Ratkin via Python-list
I just started to think from your example with method 'err' of logger 
object.
In this particular case you can check method 'err' exists or not before 
call this.



But if you mean general case ... . If for example I use some library 
which uses another library and someone just 'typo' there ...



Here is example from my code:

    calc: Calculator = Calculator()

    ...

    actions: Dict[str, Callable] = {
   "s.sysinfo":  calc.get_system_info,
   "s.setloglevel":  calc.set_log_level,
   ...
    }

    ...

    def do_action(action: str, params: Dict[str, str]) -> ActionResult:
    return await actions[action](params)


And if I make mistake and type 'calc.get_s*i*stem_info' instead 
'calc.get_s*y*stem_info. Error appears on rutime stage only.


And neither 'mypy --strict' or 'pyre' can find such error.


I guess there  is not warranty to detect such sitations in huge codebase.

It's python dynamic nature.


May be dynamic checkers can help in such situations ...


27.03.2022 20:07, Manfred Lotz пишет:

On 3/27/22 18:57, Kirill Ratkin wrote:

Hi

You can get all methods of your object and check the method you want to call is
there or not.

|methods = [method for method in dir() if
callable(getattr(, method))] if 'method_you_need' in methods:
. // BR |


I don't understand how this may help. Assume somebody has a codebase of 15T
lines of Python code. How do you want to apply your method?

But perhaps I overlook things.


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


Re: How to detect an undefined method?

2022-03-27 Thread Avi Gross via Python-list
The question seems to be how or whether you can check Python code in
advance for any instances of a method for an object being called that is
not instantiated. Right?

As Kirill points out, Python can be quite dynamic. I can think of oodles
of ways checking would not work well in a static examination of the code.

Just to mention a few, I can have a collection of objects (such as a list)
and I may iterate on it to take each object and call a specific method.
Some objects may have the method and others may not. The dynamic
code may easily include objects that conform to expectations or not.
For example, you ay be reading in saved objects from a file or objects
are being created as the user interacts. 

And is it an error if a program is written to detect and perhaps correct
errors? What if I want to display an object and in a "try" block I ask to
run one of several methods and on failure, try the next. Some objects
may have a method for full_profile() while others just might have a name()
and yet others might have no known way and will be shown as ANONYMOUS.

There also seem to be ways to extend an existing object or the entire class 
after 
it has been created. Objects with multiple inheritance also may be  headache.

So I suspect warnings for some cases make sense but a tool that catches 
everything,
maybe not easy or even possible.

You can, of course, make your code a tad more bulletproof, there are ways you 
can
have your code deliberately check if the object has that method before trying to
invoke it, or you can handle exceptions generated if it doesn't.

-Original Message-
From: Kirill Ratkin via Python-list 
To: python-list@python.org
Sent: Sun, Mar 27, 2022 2:29 pm
Subject: Re: How to detect an undefined method?


I just started to think from your example with method 'err' of logger 
object.
In this particular case you can check method 'err' exists or not before 
call this.


But if you mean general case ... . If for example I use some library 
which uses another library and someone just 'typo' there ...


Here is example from my code:

     calc: Calculator = Calculator()

     ...

     actions: Dict[str, Callable] = {
    "s.sysinfo":  calc.get_system_info,
    "s.setloglevel":  calc.set_log_level,
    ...
     }

     ...

     def do_action(action: str, params: Dict[str, str]) -> ActionResult:
     return await actions[action](params)


And if I make mistake and type 'calc.get_s*i*stem_info' instead 
'calc.get_s*y*stem_info. Error appears on rutime stage only.

And neither 'mypy --strict' or 'pyre' can find such error.


I guess there  is not warranty to detect such sitations in huge codebase.

It's python dynamic nature.


May be dynamic checkers can help in such situations ...



27.03.2022 20:07, Manfred Lotz пишет:
> On 3/27/22 18:57, Kirill Ratkin wrote:
>> Hi
>>
>> You can get all methods of your object and check the method you want to call 
>> is
>> there or not.
>>
>> |methods = [method for method in dir() if
>> callable(getattr(, method))] if 'method_you_need' in methods:
>> . // BR |
>>
> I don't understand how this may help. Assume somebody has a codebase of 15T
> lines of Python code. How do you want to apply your method?
>
> But perhaps I overlook things.
>
-- 
https://mail.python.org/mailman/listinfo/python-list

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


Set tkinter top-level window to "always on visible workspace"

2022-03-27 Thread Skip Montanaro
I have a tkinter app (Ubuntu/X11 env) whose main window should always be
displayed on the currently visible workspace. Is there some way to set that
attribute programmatically? I see that there is a tkinter.Wm class and that
Toplevel widgets have a wm_attributes method, but haven't found any
examples in the library doc or on the wider net which demonstrate control
of this particular window manager interaction. (I don't care about Windows
or Mac, at least for the time being.)

Thx,

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Set tkinter top-level window to "always on visible workspace"

2022-03-27 Thread Cameron Simpson
On 27Mar2022 16:23, Skip Montanaro  wrote:
>I have a tkinter app (Ubuntu/X11 env) whose main window should always be
>displayed on the currently visible workspace. Is there some way to set that
>attribute programmatically? I see that there is a tkinter.Wm class and that
>Toplevel widgets have a wm_attributes method, but haven't found any
>examples in the library doc or on the wider net which demonstrate control
>of this particular window manager interaction.

I fear not. That is normally a window manager-side control. So you might 
tell your window manager to keep that window on the main workspace. I 
might be wrong - there might be wm_attributes which are meant to request 
this behaviour (from the window manager), But I'm pretty sure when I was 
using FVWM I did this on the window manager side, saying "these apps 
should be on desktop N" and stuff like that.

>(I don't care about Windows
>or Mac, at least for the time being.)

I think this is window manager stuff on the Mac too, in that you can 
tell the desktop to put an app's windows on every desktop, of a specific 
desktop, or just wherever they get opened.

Hmm... Yeah, here's part of my FVWM config:

Style "sticky"  Sticky
Style "topsticky" UseStyle sticky, StaysOnTop, WindowListSkip
Style "bottomsticky" UseStyle sticky, StaysOnBottom

Style "X2x" UseStyle topsticky
Style "gkrellm" UseStyle bottomsticky

which uses the application names to specify how the WM treats them. The 
two examples are gkrellm, a load monitor, to be always on the current 
workspace, below/behind everything else, and x2x to be on every 
workspace, above everything else. (X2x runs a 1-pixel-wide full height 
window at the edge of the display to notice the mouse hit that edge, and 
to take it and drive another X11 display - thus allowing one to slide 
the mouse from the primary display to the adjacent display run by 
another computer; see also x2vnc et al).

But alas, these are WM-side controls. But maybe the WM might know about 
and honour some wm_attributes? I have no knowledge there.

Cheers,
Cameron Simpson 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Set tkinter top-level window to "always on visible workspace"

2022-03-27 Thread Skip Montanaro
> So you might tell your window manager to keep that window on the main
workspace.

Thanks. I'd forgotten about the possibility of doing this sort of thing in
the window manager config. That would certainly be fine in this case. (It's
been ages since I messed with this sort of thing.)

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list