Re: typing: property/setter and lists? [RESOLVED ERRATA]

2022-11-04 Thread Paulo da Silva

Às 07:52 de 04/11/22, dn escreveu:

On 04/11/2022 07.50, Chris Angelico wrote:

On Fri, 4 Nov 2022 at 05:48, Paulo da Silva
 wrote:


Às 05:32 de 03/11/22, Paulo da Silva escreveu:

Às 03:24 de 03/11/22, Paulo da Silva escreveu:

Hi!

And a typing problem again!!!
___
class C:
  def __init__(self):
  self.__foos=5*[0]

  @property
  def foos(self) -> list[int]:
  return self.__foos

  @foos.setter
  def foos(self,v: int):
  self.__foos=[v for __i in self.__foos]

c=C()
c.foos=5
print(c.foos)
___

mypy gives the following error:
error: Incompatible types in assignment (expression has type "int",
variable has type "List[int]")

How do I turn around this?


Changing def foos(self) -> list[int]:  to
   def foos(self) -> Union[list[int]]:

I meant, of course,
def foos(self) -> Union[list[int],int]:



Ohhh! I thought this was triggering a strange quirk of the checker in
some way...



Yes, these personal styles (?quirks) are off-putting to others.

Plus "_" means (more or less) "not used anymore"
and for most of us, a weak-identifier name such as "i" is indeed "an 
indexer/counter/... "

Thank you for the suggestions.
BTW, I am not a python pro programmer. I use it as a tool as many other 
tools and some other (few) languages.


..

...and whilst I'm griping,
"To help us to help you please copy-paste the *exact* message"
has been followed by:
"I'm sorry. A bad transposition of the text."

copy-paste for the win!
(and to keep others happy to spend their voluntary time helping you - 
more working-with-the-team thinking to consider - please)
The full original message was there. Seemed to me that that was obvious 
considering the simplicity of the subject and the illustrative toy example.

Anyway, I'm sorry.

Thank you.
Paulo


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


Re: typing: property/setter and lists?

2022-11-03 Thread Paulo da Silva

Às 07:55 de 03/11/22, dn escreveu:

On 03/11/2022 16.24, Paulo da Silva wrote:

class C:
 def __init__(self):
 self.__foos=5*[0]

 @property
 def foos(self) -> list[int]:
 return self.__foos

 @foos.setter
 def foos(self,v: int):
 self.__foos=[v for __i in self.__foos]

c=C()
c.foos=5
print(c.foos)
___

mypy gives the following error:
error: Incompatible types in assignment (expression has type "int", 
variable has type "List[int]")



To help us to help you please copy-paste the *exact* message - 
especially which line is in-question.



The above code passes without complaint in PyCharm, and executes.


However, the general rule?convention would be to establish type at the 
first mention of the identifier, eg


def __init__(self):
     self.__foos:list[int] = 5 * [ 0 ]
# or [ 0, 0, 0, 0, 0, ]


Why the "__i", and not "i", or "_"?

Just because of my personal taste.
I know that __ means (for me) a "not used anymore" var and i is an 
indexer/counter/...


Regards.
Paulo


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


Re: typing: property/setter and lists? [RESOLVED]

2022-11-03 Thread Paulo da Silva

Às 18:16 de 03/11/22, Chris Angelico escreveu:

On Fri, 4 Nov 2022 at 05:03, Paulo da Silva
 wrote:

Changing def foos(self) -> list[int]:  to
   def foos(self) -> Union[list[int]]:
fixes the problem.
Not so elegant, however!


Wait, what?!

Union[X, Y] means "X or Y"
Union[X] means "X, but don't complain if it's a @property".

Is that how it goes?

I'm sorry. A bad transposition of the text. I meant
def foos(self) -> Union[list[int],int]:

Regards.
Paulo


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


Re: typing: property/setter and lists? [RESOLVED ERRATA]

2022-11-03 Thread Paulo da Silva

Às 05:32 de 03/11/22, Paulo da Silva escreveu:

Às 03:24 de 03/11/22, Paulo da Silva escreveu:

Hi!

And a typing problem again!!!
___
class C:
 def __init__(self):
 self.__foos=5*[0]

 @property
 def foos(self) -> list[int]:
 return self.__foos

 @foos.setter
 def foos(self,v: int):
 self.__foos=[v for __i in self.__foos]

c=C()
c.foos=5
print(c.foos)
___

mypy gives the following error:
error: Incompatible types in assignment (expression has type "int", 
variable has type "List[int]")


How do I turn around this?


Changing def foos(self) -> list[int]:  to
  def foos(self) -> Union[list[int]]:

I meant, of course,
def foos(self) -> Union[list[int],int]:

Sorry.
Paulo


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


Re: typing: property/setter and lists? [RESOLVED]

2022-11-03 Thread Paulo da Silva

Às 03:24 de 03/11/22, Paulo da Silva escreveu:

Hi!

And a typing problem again!!!
___
class C:
 def __init__(self):
     self.__foos=5*[0]

 @property
 def foos(self) -> list[int]:
     return self.__foos

 @foos.setter
 def foos(self,v: int):
     self.__foos=[v for __i in self.__foos]

c=C()
c.foos=5
print(c.foos)
___

mypy gives the following error:
error: Incompatible types in assignment (expression has type "int", 
variable has type "List[int]")


How do I turn around this?


Changing def foos(self) -> list[int]:  to
 def foos(self) -> Union[list[int]]:
fixes the problem.
Not so elegant, however!

Regards.
Paulo


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


typing: property/setter and lists?

2022-11-02 Thread Paulo da Silva

Hi!

And a typing problem again!!!
___
class C:
def __init__(self):
self.__foos=5*[0]

@property
def foos(self) -> list[int]:
return self.__foos

@foos.setter
def foos(self,v: int):
self.__foos=[v for __i in self.__foos]

c=C()
c.foos=5
print(c.foos)
___

mypy gives the following error:
error: Incompatible types in assignment (expression has type "int", 
variable has type "List[int]")


How do I turn around this?

Thanks.
Paulo

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


Re: Fwd: A typing question

2022-11-01 Thread Paulo da Silva

Às 21:08 de 31/10/22, Peter J. Holzer escreveu:

On 2022-10-30 11:26:56 +0100, Peter J. Holzer wrote:

On 2022-10-29 23:59:44 +0100, Paulo da Silva wrote:

The funny thing is that if I replace foos by Foos it works because it gets
known by the initial initialization :-) !


from typing import List, Optional

class GLOBALS:
 Foos: Optional[Foos]=None

[...]

class Foos:


That seems like a bug to me.


But is it even true?

I just tried to reproduce it (should have done that before answering)
with mypy 0.942 (included in Ubuntu 22.04 LTS):

[p1]---
from typing import List, Optional

class GLOBALS:
 foos: Optional[Foos]=None

class Foo:

 def __init__(self):
 pass

class Foos:
 Foos: List[Foo]=[]
 # SOME GLOBALS ARE USED HERE

 def __init__(self):
 pass

GLOBALS.foos=Foos()
---

[p2]---
from typing import List, Optional

class GLOBALS:
 Foos: Optional[Foos]=None

class Foo:

 def __init__(self):
 pass

class Foos:
 Foos: List[Foo]=[]
 # SOME GLOBALS ARE USED HERE

 def __init__(self):
 pass

GLOBALS.Foos=Foos()
---

--- p1  2022-10-31 21:59:49.639869922 +0100
+++ p2  2022-10-31 21:58:19.815830677 +0100
@@ -1,7 +1,7 @@
  from typing import List, Optional

  class GLOBALS:
-foos: Optional[Foos]=None
+Foos: Optional[Foos]=None

  class Foo:

@@ -15,4 +15,4 @@
  def __init__(self):
  pass

-GLOBALS.foos=Foos()
+GLOBALS.Foos=Foos()

So the only difference is the capitalization of foos. And mypy accepts
both (as it probably should):

% mypy p1
Success: no issues found in 1 source file
% mypy p2
Success: no issues found in 1 source file


If you did something different, please explain what you did.


Yes for mypy.
Try to run them (python3 ).

Paulo


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


Re: Fwd: A typing question

2022-10-30 Thread Paulo da Silva

Às 17:06 de 30/10/22, Stefan Ram escreveu:

Paulo da Silva  writes:

Is there anything to do without loosing my script structure and usual
practice?


   to lose (losing): to stop having something
   to loose (loosing): to let or make loose (see next line)
   loose (adj.): not firmly attached/tied/fastened/controlled
   to loosen: similar to "to loose"


It was a keyboard bounce ;-)
How about answering the question?
Thank you.



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


Re: Fwd: A typing question

2022-10-30 Thread Paulo da Silva

Às 22:34 de 29/10/22, dn escreveu:
Out of interest, tested snippet in PyCharm, cf native-mypy. It flags the 
original:


     GLOBALS.foos: Optional[Foos]=Foos()

but not the fall-back:

     GLOBALS.foos=Foos()


Must admit, the first query coming to mind was: why is the typing taking 
place at initialisation-time, rather than within the (class) definition? 
At definition time "foos" has already been typed as None by implication!



Solution (below) will not work if the mention of Foos in GLOBALS is a 
forward-reference. Either move GLOBALS to suit, or surround "Foos" with 
quotes.

Somehow I missed this sentence the 1st. time I read this post :-(
This is good enough to me! Thank you.
I didn't know about this "quoting" thing.

Regards
Paulo


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


Re: Fwd: A typing question

2022-10-30 Thread Paulo da Silva

Às 10:26 de 30/10/22, Peter J. Holzer escreveu:

On 2022-10-29 23:59:44 +0100, Paulo da Silva wrote:

Às 22:34 de 29/10/22, dn escreveu:

Solution (below) will not work if the mention of Foos in GLOBALS is a
forward-reference.
Either move GLOBALS to suit, or surround "Foos" with quotes.

  ^^

This is the problem for me.


Quotes are a bit ugly, but why are they a problem?

[...]


The funny thing is that if I replace foos by Foos it works because it gets
known by the initial initialization :-) !


from typing import List, Optional

class GLOBALS:
 Foos: Optional[Foos]=None

[...]

class Foos:


That seems like a bug to me. What is the «Foos» in «Optional[Foos]»
referring to?

If it's the class attribute «Foos» then that's not a type and even if
its type is inferred that's not the same as «Optional[it's type]», or is
it?

If it's referring to the global symbol «Foos» (i.e. the class defined
later) that hasn't been defined yet, so it shouldn't work (or
alternatively, if forward references are allowed it should always work).


The problem is exactly this.
Is there anything to do without loosing my script structure and usual 
practice? The forward reference only is needed to the "typing thing".
Even if I declare class "Foos: pass" before, then another error arises - 
something like "already declared" below.



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


Re: A typing question

2022-10-30 Thread Paulo da Silva

Às 01:14 de 30/10/22, Thomas Passin escreveu:

On 10/29/2022 1:45 PM, Paulo da Silva wrote:

Hi!

Consider this simple script ...

___
from typing import List, Optional

class GLOBALS:
 foos=None

class Foo:

 def __init__(self):
 pass

class Foos:
 Foos: List[Foo]=[]
 # SOME GLOBALS ARE USED HERE in a real script

 def __init__(self):
 pass

GLOBALS.foos: Optional[Foos]=Foos()
___

Running mypy on it:
pt9.py:18: error: Type cannot be declared in assignment to non-self 
attribute
pt9.py:18: error: Incompatible types in assignment (expression has 
type "Foos", variable has type "None")

Line  18 is last line and pt9.py is the scrip.

Replacing last line by
GLOBALS.foos=Foos()
and running mypy still gives the second error.
pt9.py:18: error: Incompatible types in assignment (expression has 
type "Foos", variable has type "None")


What is the common practice in these cases?

Thank you.



I don't understand

class Foos:
  Foos: List[Foo]=[]

If "Foos" is supposed to be a class attribute, then it cannot have the 
same name as the class.

Yes it can.
You can refer it anywhere by Foos.Foos as a list of Foo elements.


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


Re: Fwd: A typing question

2022-10-30 Thread Paulo da Silva

Às 02:32 de 30/10/22, dn escreveu:

On 30/10/2022 11.59, Paulo da Silva wrote:
Solution (below) will not work if the mention of Foos in GLOBALS is a 
forward-reference. Either move GLOBALS to suit, or surround "Foos" 
with quotes.
This is the problem for me. So far, without typing, I used to have 
some config and globals classes, mostly to just group definitions an 
make the program more readable. A matter of taste and style.


Agreed, a good practice.

Thank you.



Now, "typing" is breaking this, mostly because of this forward 
reference issue.


As a first step, use the quotation-marks to indicate that such will be 
defined later in the code:-



class GLOBALS:
    Foos: Optional[Foos]=None 


class GLOBALS:
     Foos: Optional["Foos"]=None


Later, as gather (typing) expertise, can become more sophisticated, 
as-and-when...



The funny thing is that if I replace foos by Foos it works because it 
gets known by the initial initialization :-) !


Is the objective to write (good) code, or merely to satisfy the 
type-checker?


Something that is misleading is not going to be appreciated by others 
(including the +6-months you), eg


a = a + 1   # decrement total

Typing is not compulsory, and has been designed so that we can implement 
it a bit at a time, eg only one function amongst many contained by a 
module - if that's the only code that requires maintenance/update.


Best not to create "technical debt" though!

The main idea is to eventually catch some, otherwise "hidden", errors 
and produce better and cleaner code. Documentation is also a must.


Regards


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


Re: Fwd: A typing question

2022-10-29 Thread Paulo da Silva

Às 22:34 de 29/10/22, dn escreveu:
Out of interest, tested snippet in PyCharm, cf native-mypy. It flags the 
original:


     GLOBALS.foos: Optional[Foos]=Foos()

but not the fall-back:

     GLOBALS.foos=Foos()


Must admit, the first query coming to mind was: why is the typing taking 
place at initialisation-time, rather than within the (class) definition? 
At definition time "foos" has already been typed as None by implication!



Solution (below) will not work if the mention of Foos in GLOBALS is a 
forward-reference. Either move GLOBALS to suit, or surround "Foos" with 
quotes.
This is the problem for me. So far, without typing, I used to have some 
config and globals classes, mostly to just group definitions an make the 
program more readable. A matter of taste and style.
Now, "typing" is breaking this, mostly because of this forward reference 
issue.
The funny thing is that if I replace foos by Foos it works because it 
gets known by the initial initialization :-) !



from typing import List, Optional

class GLOBALS:
Foos: Optional[Foos]=None

class Foo:

def __init__(self):
pass

class Foos:
Foos: List[Foo]=[]
# SOME GLOBALS ARE USED HERE

def __init__(self):
pass

GLOBALS.Foos=Foos()







Also, these days (Python version allowing) importing "List" is 
unnecessary. Instead could use "list".




On 30/10/2022 10.23, Sam Ezeh wrote:

Do you want the following?

```
from typing import List, Optional


class GLOBALS:
 foos: Optional[Foos] = None


class Foo:
 def __init__(self):
 pass


class Foos:
 Foos: List[Foo] = []

 def __init__(self):
 pass


GLOBALS.foos = Foos()
```

Kind regards,
Sam Ezeh

On Sat, 29 Oct 2022 at 22:13, Paulo da Silva <
p_d_a_s_i_l_v_a...@nonetnoaddress.pt> wrote:


Hi!

Consider this simple script ...

___
from typing import List, Optional

class GLOBALS:
  foos=None

class Foo:

  def __init__(self):
  pass

class Foos:
  Foos: List[Foo]=[]
  # SOME GLOBALS ARE USED HERE in a real script

  def __init__(self):
  pass

GLOBALS.foos: Optional[Foos]=Foos()
___

Running mypy on it:
pt9.py:18: error: Type cannot be declared in assignment to non-self
attribute
pt9.py:18: error: Incompatible types in assignment (expression has type
"Foos", variable has type "None")
Line  18 is last line and pt9.py is the scrip.

Replacing last line by
GLOBALS.foos=Foos()
and running mypy still gives the second error.
pt9.py:18: error: Incompatible types in assignment (expression has type
"Foos", variable has type "None")

What is the common practice in these cases?

Thank you.

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






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


A typing question

2022-10-29 Thread Paulo da Silva

Hi!

Consider this simple script ...

___
from typing import List, Optional

class GLOBALS:
foos=None

class Foo:

def __init__(self):
pass

class Foos:
Foos: List[Foo]=[]
# SOME GLOBALS ARE USED HERE in a real script

def __init__(self):
pass

GLOBALS.foos: Optional[Foos]=Foos()
___

Running mypy on it:
pt9.py:18: error: Type cannot be declared in assignment to non-self 
attribute
pt9.py:18: error: Incompatible types in assignment (expression has type 
"Foos", variable has type "None")

Line  18 is last line and pt9.py is the scrip.

Replacing last line by
GLOBALS.foos=Foos()
and running mypy still gives the second error.
pt9.py:18: error: Incompatible types in assignment (expression has type 
"Foos", variable has type "None")


What is the common practice in these cases?

Thank you.

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


Re: Typing: Is there a "cast operator"?

2022-10-23 Thread Paulo da Silva

Às 23:56 de 23/10/22, Cameron Simpson escreveu:
On 23Oct2022 21:36, Paulo da Silva 
 wrote:

I am in the process of "typing" of some of my scripts.
Using it should help a lot to avoid some errors.
But this is new for me and I'm facing some problems.

Let's I have the following code (please don't look at the program 
content):


f=None  # mypy naturally assumes Optional(int) because later, at open, 
it is assigned an int.

..
if f is None:
f=os.open(...
..
if f is not None:
os.write(f, ...)
..
if f is not None:
os.close(f)

When I use mypy, it claims
Argument 1 to "write" has incompatible type "Optional[int]"; expected 
"int"
Argument 1 to "close" has incompatible type "Optional[int]"; expected 
"int"


How to solve this?
Is there a way to specify that when calling os.open f is an int only?

I use None a lot for specify uninitialized vars.


Maybe you shouldn't. The other way is to just not initialise the var at 
all. You could then just specify a type. Example:


    Python 3.8.13 (default, Aug 11 2022, 15:46:53)
    [Clang 12.0.0 (clang-1200.0.32.29)] on darwin
    Type "help", "copyright", "credits" or "license" for more
information.

    >>> f:int
    >>> f
    Traceback (most recent call last):
  File "", line 1, in 
    NameError: name 'f' is not defined
    >>>

So now `f` has `int` type definitely (for `mypy`'s purposes), and if 
used before assignment raises a distinctive error (versus having the 
value `None`, which you might then pass around, and perhaps successfully 
use in some contexts).


It is probably better on the whole to specify types up front rather than 
relying on `mypy` or similar to infer them. That way (a) you're stating 
your intent and (b) not relying on an inferred type, which if you've got 
bugs may be inferred _wrong_. If `mypy` infers a type incorrectly all 
the subsequent checks will also be flawed, perhaps subtly.



Yes.
I also use to make f unavailable (f=None) when something goes wrong and 
I don't want to stop the script but of course I could use "del f". I 
also need to care about using "try", which might be better than "if" tests.

A thing to think of ...

Thanks.
Paulo


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


Re: Typing: Is there a "cast operator"? [RESOLVED]

2022-10-23 Thread Paulo da Silva

Às 21:36 de 23/10/22, Paulo da Silva escreveu:

Hello!

I am in the process of "typing" of some of my scripts.
Using it should help a lot to avoid some errors.
But this is new for me and I'm facing some problems.

Let's I have the following code (please don't look at the program content):

f=None  # mypy naturally assumes Optional(int) because later, at open, 
it is assigned an int.

..
if f is None:
 f=os.open(...
..
if f is not None:
 os.write(f, ...)
..
if f is not None:
 os.close(f)

When I use mypy, it claims
Argument 1 to "write" has incompatible type "Optional[int]"; expected "int"
Argument 1 to "close" has incompatible type "Optional[int]"; expected "int"

How to solve this?
Is there a way to specify that when calling os.open f is an int only?
And yes there is! Exactly the "cast" operator. A mistype led me to wrong 
search results. I'm sorry.


So, in the above code, we have to do:
os.write(cast(int,f), ...)
and
os.close(cast(int,f), ...)

Regards.
Paulo



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


Re: A trivial question that I don't know - document a function/method

2022-10-23 Thread Paulo da Silva

Às 21:58 de 22/10/22, Paulo da Silva escreveu:

Hi all!

What is the correct way, if any, of documenting a function/method?



Thank you all for the, valuable as usual, suggestions.
I am now able to make my choices.

Paulo


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


Typing: Is there a "cast operator"?

2022-10-23 Thread Paulo da Silva

Hello!

I am in the process of "typing" of some of my scripts.
Using it should help a lot to avoid some errors.
But this is new for me and I'm facing some problems.

Let's I have the following code (please don't look at the program content):

f=None  # mypy naturally assumes Optional(int) because later, at open, 
it is assigned an int.

..
if f is None:
f=os.open(...
..
if f is not None:
os.write(f, ...)
..
if f is not None:
os.close(f)

When I use mypy, it claims
Argument 1 to "write" has incompatible type "Optional[int]"; expected "int"
Argument 1 to "close" has incompatible type "Optional[int]"; expected "int"

How to solve this?
Is there a way to specify that when calling os.open f is an int only?

I use None a lot for specify uninitialized vars.

Thank you.

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


A trivial question that I don't know - document a function/method

2022-10-22 Thread Paulo da Silva

Hi all!

What is the correct way, if any, of documenting a function/method?

1.
def foo(a,b):
""" A description.
a: Whatever 1
b: Whatever 2
"""
...

2.
def foo(a,b):
""" A description.
a -- Whatever 1
b -- Whatever 2
"""
...

3.
def foo(a,b):
""" A description.
@param a: Whatever 1
@param b: Whatever 2
"""
...

4.
def foo(a,b):
""" A description.
:param a: Whatever 1
:param b: Whatever 2
"""
...

5.
Any other ...

Any comments/suggestions are welcome.
Thanks.
Paulo

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


Re: Find the path of a shell command [POSTPONED]

2022-10-12 Thread Paulo da Silva

Às 05:00 de 12/10/22, Paulo da Silva escreveu:

Hi!

The simple question: How do I find the full path of a shell command 
(linux), i.e. how do I obtain the corresponding of, for example,

"type rm" in command line?

The reason:
I have python program that launches a detached rm. It works pretty well 
until it is invoked by cron! I suspect that for cron we need to specify 
the full path.
Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? 
What about other commands?



For now I will postpone this problem.
I just wrote a small script to delete a dir using rm and it works even 
under cron!
There is another problem involved. The script, works fine except when 
launched by cron! Why?

I'll have to look into this later when I have more time.
For now I solved the problem using a complementary shell script.

Thank you very much to those who responded.
Paulo


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


Re: Find the path of a shell command

2022-10-12 Thread Paulo da Silva

Às 22:38 de 12/10/22, Jon Ribbens escreveu:

On 2022-10-12, Jon Ribbens  wrote:

On 2022-10-12, Paulo da Silva  wrote:

Às 19:14 de 12/10/22, Jon Ribbens escreveu:

On 2022-10-12, Paulo da Silva  wrote:

Às 05:00 de 12/10/22, Paulo da Silva escreveu:

Hi!

The simple question: How do I find the full path of a shell command
(linux), i.e. how do I obtain the corresponding of, for example,
"type rm" in command line?

The reason:
I have python program that launches a detached rm. It works pretty well
until it is invoked by cron! I suspect that for cron we need to specify
the full path.
Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin?
What about other commands?


Thank you all who have responded so far.
I think that the the suggestion of searching the PATH env seems the best.
Another thing that I thought of is that of the 'which', but, to avoid
the mentioned recurrent problem of not knowing where 'which' is I would
use 'type' instead. 'type' is a bash (sh?) command.


If you're using subprocess.run / subprocess.Popen then the computer is
*already* searching PATH for you.

Yes, and it works out of cron.

Your problem must be that your cron
job is being run without PATH being set, perhaps you just need to edit
your crontab to set PATH to something sensible.

I could do that, but I am using /etc/cron.* for convenience.


Or just hard-code your
program to run '/bin/rm' explicitly, which should always work (unless
you're on Windows, of course!)

It can also be in /bin, at least.


I assume you mean /usr/bin. But it doesn't matter. As already
discussed, even if 'rm' is in /usr/bin, it will be in /bin as well
(or /usr/bin and /bin will be symlinks to the same place).


A short idea is to just check /bin/rm and /usr/bin/rm, but I prefer
searching thru PATH env. It only needs to do that once.


I cannot think of any situation in which that will help you. But if for
some reason you really want to do that, you can use the shutil.which()
function from the standard library:

 >>> import shutil
 >>> shutil.which('rm')
 '/usr/bin/rm'


Actually if I'm mentioning shutil I should probably mention
shutil.rmtree() as well, which does the same as 'rm -r', without
needing to find or run any other executables.

Except that you can't have parallel tasks, at least in an easy way.
Using Popen I just launch rm's and end the script.


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


Re: Find the path of a shell command

2022-10-12 Thread Paulo da Silva

Às 20:09 de 12/10/22, Antoon Pardon escreveu:



Op 12/10/2022 om 18:49 schreef Paulo da Silva:

Às 05:00 de 12/10/22, Paulo da Silva escreveu:

Hi!

The simple question: How do I find the full path of a shell command 
(linux), i.e. how do I obtain the corresponding of, for example,

"type rm" in command line?

The reason:
I have python program that launches a detached rm. It works pretty 
well until it is invoked by cron! I suspect that for cron we need to 
specify the full path.
Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? 
What about other commands?



Thank you all who have responded so far.
I think that the the suggestion of searching the PATH env seems the best.


I fear that won't work.

If it doesn't work in cron, that probably means, PATH is not set 
properly in your cron environment. And if PATH is not set properly, 
searching it explicitely won't work either.



It seems you are right :-( I didn't think of that!
Does 'type' bash command work? I don't know how bash 'type' works.
I need to do some tests.
Thanks
Paulo



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


Re: Find the path of a shell command

2022-10-12 Thread Paulo da Silva

Às 19:14 de 12/10/22, Jon Ribbens escreveu:

On 2022-10-12, Paulo da Silva  wrote:

Às 05:00 de 12/10/22, Paulo da Silva escreveu:

Hi!

The simple question: How do I find the full path of a shell command
(linux), i.e. how do I obtain the corresponding of, for example,
"type rm" in command line?

The reason:
I have python program that launches a detached rm. It works pretty well
until it is invoked by cron! I suspect that for cron we need to specify
the full path.
Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin?
What about other commands?


Thank you all who have responded so far.
I think that the the suggestion of searching the PATH env seems the best.
Another thing that I thought of is that of the 'which', but, to avoid
the mentioned recurrent problem of not knowing where 'which' is I would
use 'type' instead. 'type' is a bash (sh?) command.


If you're using subprocess.run / subprocess.Popen then the computer is
*already* searching PATH for you.

Yes, and it works out of cron.

Your problem must be that your cron
job is being run without PATH being set, perhaps you just need to edit
your crontab to set PATH to something sensible.

I could do that, but I am using /etc/cron.* for convenience.


Or just hard-code your
program to run '/bin/rm' explicitly, which should always work (unless
you're on Windows, of course!)

It can also be in /bin, at least.
A short idea is to just check /bin/rm and /usr/bin/rm, but I prefer 
searching thru PATH env. It only needs to do that once.



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


Re: Find the path of a shell command

2022-10-12 Thread Paulo da Silva

Às 20:16 de 12/10/22, 2qdxy4rzwzuui...@potatochowder.com escreveu:

On 2022-10-12 at 17:43:18 +0100,
Paulo da Silva  wrote:


Às 17:22 de 12/10/22, Tilmann Hentze escreveu:

Paulo da Silva  schrieb:

I have python program that launches a detached rm. It works pretty well
until it is invoked by cron! I suspect that for cron we need to specify
the full path.


Probably you could use os.unlink[1] with no problem.

No, because I need to launch several rm's that keep running after the script
ends.


rm doesn't take that long.  Why are you detaching them?


Because the use of "rm -rf" here is to remove full dirs, mostly in 
external drives, each reaching more than hundreds thousand files.




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


Re: Find the path of a shell command

2022-10-12 Thread Paulo da Silva

Às 17:22 de 12/10/22, Tilmann Hentze escreveu:

Paulo da Silva  schrieb:

I have python program that launches a detached rm. It works pretty well
until it is invoked by cron! I suspect that for cron we need to specify
the full path.


Probably you could use os.unlink[1] with no problem.
No, because I need to launch several rm's that keep running after the 
script ends.



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


Re: Find the path of a shell command

2022-10-12 Thread Paulo da Silva

Às 05:00 de 12/10/22, Paulo da Silva escreveu:

Hi!

The simple question: How do I find the full path of a shell command 
(linux), i.e. how do I obtain the corresponding of, for example,

"type rm" in command line?

The reason:
I have python program that launches a detached rm. It works pretty well 
until it is invoked by cron! I suspect that for cron we need to specify 
the full path.
Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? 
What about other commands?



Thank you all who have responded so far.
I think that the the suggestion of searching the PATH env seems the best.
Another thing that I thought of is that of the 'which', but, to avoid 
the mentioned recurrent problem of not knowing where 'which' is I would 
use 'type' instead. 'type' is a bash (sh?) command.


Thanks
Paulo


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


Find the path of a shell command

2022-10-12 Thread Paulo da Silva

Hi!

The simple question: How do I find the full path of a shell command 
(linux), i.e. how do I obtain the corresponding of, for example,

"type rm" in command line?

The reason:
I have python program that launches a detached rm. It works pretty well 
until it is invoked by cron! I suspect that for cron we need to specify 
the full path.
Of course I can hardcode /usr/bin/rm. But, is rm always in /usr/bin? 
What about other commands?


Thanks for any comments/responses.
Paulo

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


Re: Subtract n months from datetime

2022-06-22 Thread Paulo da Silva

Às 19:47 de 22/06/22, Marco Sulla escreveu:

The package arrow has a simple shift method for months, weeks etc

https://arrow.readthedocs.io/en/latest/#replace-shift


At first look it seems pretty good! I didn't know it.
Thank you Marco.

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


Re: Subtract n months from datetime [Why?]

2022-06-22 Thread Paulo da Silva

Às 20:25 de 22/06/22, Barry Scott escreveu:




On 22 Jun 2022, at 17:59, Paulo da Silva  
wrote:

Às 05:29 de 21/06/22, Paulo da Silva escreveu:

As a general response to some comments ...

Suppose we need to delete records from a database older than ...
Today, it's usual to specify days. For example you have to keep some gov papers 
for 90 days. This seems to come from computers era. In our minds, however, we 
immediately think 90 days=3 months.
For example, one may want to delete some files older than 9 months. It's far 
more intuitive than 270 days.
When we talk about years it is still going. For example I need to keep my 
receipts for 5 years because IRS audits.
Accepting this, it's intuitive, for example, that 3 months before July, 31 is 
April, 30.
The same happens for the years. 5 years before February, 29 is February, 28.


The advantage of 30 days, 90 days etc is that a contract or law does not need 
to tell you
how to deal with the problems of calendar months.

As you say in peoples thoughts that 1 month or 3 months etc. But an accounts 
department
will know how to to the number of days till they have to pay up.

Yes. But my point is to justify why I want months. And it depends on the 
application.
Let's suppose a program for Joe User to clean something - files, for 
example. There are no rules except for the comfort of the user. He would 
prefer to be able to say 9 months back instead of 270 days. And by 9 
months, he expects to count down 9 months. Not 270 days.

That's what happens with the script I am writing.

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


Re: Subtract n months from datetime [Why?]

2022-06-22 Thread Paulo da Silva

Às 05:29 de 21/06/22, Paulo da Silva escreveu:

As a general response to some comments ...

Suppose we need to delete records from a database older than ...
Today, it's usual to specify days. For example you have to keep some gov 
papers for 90 days. This seems to come from computers era. In our minds, 
however, we immediately think 90 days=3 months.
For example, one may want to delete some files older than 9 months. It's 
far more intuitive than 270 days.
When we talk about years it is still going. For example I need to keep 
my receipts for 5 years because IRS audits.
Accepting this, it's intuitive, for example, that 3 months before July, 
31 is April, 30.

The same happens for the years. 5 years before February, 29 is February, 28.

Again, this is my opinion and that's the way I like it :-)
Regards
Paulo
--
https://mail.python.org/mailman/listinfo/python-list


Re: Subtract n months from datetime

2022-06-21 Thread Paulo da Silva

Às 05:44 de 21/06/22, Paul Bryan escreveu:

Here's how my code does it:


import calendar

def add_months(value: date, n: int):
   """Return a date value with n months added (or subtracted if
negative)."""
   year = value.year + (value.month - 1 + n) // 12
   month = (value.month - 1 + n) % 12 + 1
   day = min(value.day, calendar.monthrange(year, month)[1])
   return date(year, month, day)

Paul

I have a datetime, not a date.
Anyway, the use of calendar.monthrange simplifies the task a lot.

Assuming dtnow has the current datetime and dtn the number of months to 
be subtracted, here is my solution (the code was not cleaned yet - just 
a test):

dtnow_t=list(dtnow.timetuple()[:6]+(dtnow.microsecond,))
y=dtnow_t[0] # y,m,d,*_=dtnow_t seems slower
m=dtnow_t[1]
d=dtnow_t[2]
dy,dm=divmod(dtn,12)
y-=dy
m-=dm
if m<1:
m+=12
y-=1
daysinmonth=calendar.monthrange(y,m)[1]
d=min(d,daysinmonth)
dtnow_t[0]=y
dtnow_t[1]=m
dtnow_t[2]=d
bt=datetime.datetime(*dtnow_t)

Any comments are welcome.

Thank you.
Paulo




On Tue, 2022-06-21 at 05:29 +0100, Paulo da Silva wrote:

Hi!

I implemented a part of a script to subtract n months from datetime.
Basically I subtracted n%12 from year and n//12 from the month adding
12
months when it goes<=0. Then used try when converting to datetime
again.
So, if the day is for example 31 for a 30 days month it raises a
ValuError exception. Then I subtract 1 to day and repeat.

The code seems too naive and very very complicated!
What is the best way to achieve this? Any existent module?

At the very end, what I want is to subtract nx where x can be y, m,
w, d
for respectively years, months, weeks or days.

I feel I am missing something here ...

Thanks.
Paulo





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


Subtract n months from datetime

2022-06-20 Thread Paulo da Silva

Hi!

I implemented a part of a script to subtract n months from datetime.
Basically I subtracted n%12 from year and n//12 from the month adding 12 
months when it goes<=0. Then used try when converting to datetime again. 
So, if the day is for example 31 for a 30 days month it raises a 
ValuError exception. Then I subtract 1 to day and repeat.


The code seems too naive and very very complicated!
What is the best way to achieve this? Any existent module?

At the very end, what I want is to subtract nx where x can be y, m, w, d 
for respectively years, months, weeks or days.


I feel I am missing something here ...

Thanks.
Paulo

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


Re: "CPython"

2022-06-20 Thread Paulo da Silva

Às 03:20 de 21/06/22, MRAB escreveu:

On 2022-06-21 02:33, Chris Angelico wrote:

On Tue, 21 Jun 2022 at 11:13, Paulo da Silva
 wrote:


Às 20:01 de 20/06/22, Paulo da Silva escreveu:
> Às 18:19 de 20/06/22, Stefan Ram escreveu:
>>    The same personality traits that make people react
>>    to troll postings might make them spread unconfirmed
>>    ideas about the meaning of "C" in "CPython".
>>
>>    The /core/ of CPython is written in C.
>>
>>    CPython is the /canonical/ implementation of Python.
>>
>>    The "C" in "CPython" stands for C.
>>
>>
>
> Not so "unconfirmed"!
> Look at this article, I recently read:
> 
https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ 


>
>
> There is a sentence in ther that begins with "CPython, short for Core
> Python, a reference implementation that other Python distributions are
> derived from, ...".
>
> Anyway, I wrote "IMHO".
>
> Do you have any credible reference to your assertion "The "C" in
> "CPython" stands for C."?
>
> Thank you.

Well ... I read the responses and they are not touching the point!
I just answered, with my opinion based on articles I have read in the
past. Certainly I could not be sure. That's why I responded as an
opinion (IMHO) and not as an assertion.
Stefan Ram responded with a, at least, not very polite post.
That's why I needed to somehow "defend" why I posted that response, and,
BTW, trying to learn why he said that the C in CPython means "written 
in C".


I still find very strange, to not say weird, that a compiler or
interpreter has a name based in the language it was written. But, again,
is just my opinion and nothing more.



Not sure why it's strange. The point is to distinguish "CPython" from
"Jython" or "Brython" or "PyPy" or any of the other implementations.
Yes, CPython has a special place because it's the reference
implementation and the most popular, but the one thing that makes it
distinct from all the others is that it's implemented in C.

And just to make it clear, the interpreter/compiler _itself_ is still 
called "python". "CPython" is a name/term that was applied retroactively 
to that particular implementation when another implementation appeared.
Yes, but that does not necessarily means that the C has to refer to the 
language of implementation. It may well be a "core" reference to 
distinguish that implementation from others with different behaviors.


Let's say they reimplement "reference python" CPython in Rust. What is 
better? Change the "reference python" CPython name to RPython, for 
example, or let it as CPython?

It's my opinion that it should stay as CPython.
After all who cares in which language it is implemented?

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


Re: "CPython"

2022-06-20 Thread Paulo da Silva

Às 02:33 de 21/06/22, Chris Angelico escreveu:

On Tue, 21 Jun 2022 at 11:13, Paulo da Silva
 wrote:


Às 20:01 de 20/06/22, Paulo da Silva escreveu:

Às 18:19 de 20/06/22, Stefan Ram escreveu:

The same personality traits that make people react
to troll postings might make them spread unconfirmed
ideas about the meaning of "C" in "CPython".

The /core/ of CPython is written in C.

CPython is the /canonical/ implementation of Python.

The "C" in "CPython" stands for C.




Not so "unconfirmed"!
Look at this article, I recently read:
https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/


There is a sentence in ther that begins with "CPython, short for Core
Python, a reference implementation that other Python distributions are
derived from, ...".

Anyway, I wrote "IMHO".

Do you have any credible reference to your assertion "The "C" in
"CPython" stands for C."?

Thank you.


Well ... I read the responses and they are not touching the point!
I just answered, with my opinion based on articles I have read in the
past. Certainly I could not be sure. That's why I responded as an
opinion (IMHO) and not as an assertion.
Stefan Ram responded with a, at least, not very polite post.
That's why I needed to somehow "defend" why I posted that response, and,
BTW, trying to learn why he said that the C in CPython means "written in C".

I still find very strange, to not say weird, that a compiler or
interpreter has a name based in the language it was written. But, again,
is just my opinion and nothing more.



Not sure why it's strange. The point is to distinguish "CPython" from
"Jython" or "Brython" or "PyPy" or any of the other implementations.

Notice that they are, for example, Jython and not JPython.
There is also Cython that is a different thing.

And YES. You have the right to not feel that as strange.

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


Re: "CPython"

2022-06-20 Thread Paulo da Silva

Às 20:01 de 20/06/22, Paulo da Silva escreveu:

Às 18:19 de 20/06/22, Stefan Ram escreveu:

   The same personality traits that make people react
   to troll postings might make them spread unconfirmed
   ideas about the meaning of "C" in "CPython".

   The /core/ of CPython is written in C.

   CPython is the /canonical/ implementation of Python.

   The "C" in "CPython" stands for C.




Not so "unconfirmed"!
Look at this article, I recently read:
https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/ 



There is a sentence in ther that begins with "CPython, short for Core 
Python, a reference implementation that other Python distributions are 
derived from, ...".


Anyway, I wrote "IMHO".

Do you have any credible reference to your assertion "The "C" in 
"CPython" stands for C."?


Thank you.


Well ... I read the responses and they are not touching the point!
I just answered, with my opinion based on articles I have read in the 
past. Certainly I could not be sure. That's why I responded as an 
opinion (IMHO) and not as an assertion.

Stefan Ram responded with a, at least, not very polite post.
That's why I needed to somehow "defend" why I posted that response, and, 
BTW, trying to learn why he said that the C in CPython means "written in C".


I still find very strange, to not say weird, that a compiler or 
interpreter has a name based in the language it was written. But, again, 
is just my opinion and nothing more.


I rest my case.
Thank you all.
--
https://mail.python.org/mailman/listinfo/python-list


Re: "CPython"

2022-06-20 Thread Paulo da Silva

Às 18:19 de 20/06/22, Stefan Ram escreveu:

   The same personality traits that make people react
   to troll postings might make them spread unconfirmed
   ideas about the meaning of "C" in "CPython".

   The /core/ of CPython is written in C.

   CPython is the /canonical/ implementation of Python.

   The "C" in "CPython" stands for C.




Not so "unconfirmed"!
Look at this article, I recently read:
https://www.analyticsinsight.net/cpython-to-step-over-javascript-in-developing-web-applications/

There is a sentence in ther that begins with "CPython, short for Core 
Python, a reference implementation that other Python distributions are 
derived from, ...".


Anyway, I wrote "IMHO".

Do you have any credible reference to your assertion "The "C" in 
"CPython" stands for C."?


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


Re: What's up with modern Python programmers rewriting everything in Rust?

2022-06-20 Thread Paulo da Silva

Às 15:07 de 19/06/22, jan Anja escreveu:

Dude, it's called CPython for a reason.


IMHO CPython means Core Python, not C Python.

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


Re: What's up with modern Python programmers rewriting everything in Rust?

2022-06-20 Thread Paulo da Silva

Às 16:40 de 20/06/22, Dennis Lee Bieber escreveu:

On Mon, 20 Jun 2022 15:54:29 +0100, Paulo da Silva
 declaimed the following:


Às 15:07 de 19/06/22, jan Anja escreveu:

Dude, it's called CPython for a reason.


IMHO CPython means Core Python, not C Python.


It is, as I recall, a term for the reference implementation of Python,
which was written in C... In contrast to things like Jython -- Python
implemented using Java.


Yes, it is a reference. That's why it is called "Core Python". The "C" 
has nothing to do with the C programming language. It may well be 
written in any language. So far it is "C" language.

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


pandas (in jupyter?) problem

2022-05-06 Thread Paulo da Silva

Hi all!

I'm having the following problem. Consider the code (the commented or 
the not commented which I think do the same things):


#for col in missing_cols:
#df[col] = np.nan

df=df.copy()
df[missing_cols]=np.nan

df has about 2 cols and len(missing_cols) is about 18000.

I'm getting lots (1 by missing_col?) of the following message from 
ipykernel:


"PerformanceWarning: DataFrame is highly fragmented.  This is usually 
the result of calling `frame.insert` many times, which has poor 
performance.  Consider joining all columns at once using 
pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = 
frame.copy()`

  df[missing_cols]=np.nan"


At first I didn't have df=df.copy(). I added it later, but the same problem.

This slows down the code a lot, perhaps because jupyter is taking too 
much time issuing these messages!


Thanks for any comments.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Unpacking lists in a f string

2022-02-09 Thread Paulo da Silva

Às 02:17 de 09/02/22, Paulo da Silva escreveu:

Hi!

Let's say I have two lists of equal length but with a variable number of 
elements. For ex.:


l1=['a','b','c']
l2=['j','k','l']

I want to build a string like this
"foo a j, b k, c l bar"

Is it possible to achieve this with f strings or any other 
simple/efficient way?


Thanks for any help/comments.


Thank you for your responses.
--
https://mail.python.org/mailman/listinfo/python-list


Unpacking lists in a f string

2022-02-09 Thread Paulo da Silva

Hi!

Let's say I have two lists of equal length but with a variable number of 
elements. For ex.:


l1=['a','b','c']
l2=['j','k','l']

I want to build a string like this
"foo a j, b k, c l bar"

Is it possible to achieve this with f strings or any other 
simple/efficient way?


Thanks for any help/comments.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Writing a package

2022-02-04 Thread Paulo da Silva

Às 02:01 de 05/02/22, Cameron Simpson escreveu:

On 05Feb2022 00:37, Paulo da Silva  wrote:

Let's say I have a dir src containing another dir named foo and a
script test.py.

So, I have
src/foo (dir)
src/test.py (script)

test.py has the folloing code:

import foo as f
c=f.C()

I am inside src and want to run python test.py.

How can I create the class C inside src/foo dir if it is possible at
all?


Define it in the file "src/foo/__init__.py".

When you go:

 import blah

Python reaches for the file "blah.py" or "blah/__init__.py" (this second
path is for "packages").



Yes, thank you.
--
https://mail.python.org/mailman/listinfo/python-list


Writing a package

2022-02-04 Thread Paulo da Silva

Hello!

Let's say I have a dir src containing another dir named foo and a script 
test.py.


So, I have
src/foo (dir)
src/test.py (script)

test.py has the folloing code:

import foo as f
c=f.C()

I am inside src and want to run python test.py.

How can I create the class C inside src/foo dir if it is possible at all?

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


Re: Avoid nested SIGINT handling

2021-11-11 Thread Paulo da Silva
Às 06:22 de 11/11/21, Chris Angelico escreveu:
> On Thu, Nov 11, 2021 at 5:01 PM Jon Ribbens via Python-list
>  wrote:
>>
>> On 2021-11-10, Paulo da Silva  wrote:
>>> Hi!
>>>
>>> How do I handle a SIGINT (or any other signal) avoid nesting?
>>
>> I don't think you need to. Python will only call signal handlers in
>> the main thread, so a handler can't be executed while another handler
>> is running anyway.
> 
> Threads aren't the point here - signals happen immediately.
> 
> Would it be easier to catch KeyboardInterrupt and do your processing
> there, rather than actually catching SIGINT?
> 
> I'd recommend just trying what you have, and seeing if it's reentrant.
> My suspicion is that it isn't, on a technical level (the Python
> function will be queued for when it's safe to call it - probably after
> the next bytecode instruction), but that your own code will still need
> to worry about reentrancy.
> 
OK, thank you
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Avoid nested SIGINT handling

2021-11-10 Thread Paulo da Silva
Às 21:55 de 10/11/21, Jon Ribbens escreveu:
> On 2021-11-10, Paulo da Silva  wrote:
>> Hi!
>>
>> How do I handle a SIGINT (or any other signal) avoid nesting?
> 
> I don't think you need to. Python will only call signal handlers in
> the main thread, so a handler can't be executed while another handler
> is running anyway.
> 

Do you mean that if I issue a ctrl+c while the previous one is
"processing" it is held until, at least, the "processing" returns?
-- 
https://mail.python.org/mailman/listinfo/python-list


Avoid nested SIGINT handling

2021-11-10 Thread Paulo da Silva
Hi!

How do I handle a SIGINT (or any other signal) avoid nesting?

Does this work?

class STATUS:
InInt=False

def SIGINT_handler(sn,f):
if STATUS.InInt: return
STATUS.InInt=True
process_int()
STATUS.InInt=False

Thanks for any suggestions.
Paulo
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New assignmens ...

2021-10-22 Thread Paulo da Silva
Às 20:34 de 22/10/21, Chris Angelico escreveu:
> On Sat, Oct 23, 2021 at 6:24 AM Jon Ribbens via Python-list
>  wrote:
>>
>> On 2021-10-22, Stefan Ram  wrote:
>>> Paulo da Silva  writes:
>>>> Why doesn't this work
>>>>  if (self.ctr:=self.ctr-1)<=0:
>>>> while this works
>>>>  if (ctr:=ctr-1)<=0:
>>>
>>>   assignment_expression ::=  [identifier ":="] expression,
>>>   but the attribute references "self.ctr" is no identifier!
>>
>> This seems a surprising omission. You'd expect at least 'attributeref'
>> and 'subscription' to be allowed, if not the whole of 'target'.
> 
> That's not the primary use-case for assignment expressions, and they
> were highly controversial. It is much easier to expand it afterwards
> than to restrict it, or to have the feature rejected because people
> are scared of some small aspect of it.
> 
> If you want to propose relaxing the restrictions, make your use-case
> and attempt to convince people of the value.
> 
Well, I didn't follow the discussion of this new feature, but the reason
I can see behind allowing it seems so valid for for ctr:=ctr-1 as for
self.ctr:=self.ctr-1. The kind of use is exactly the same. One is for a
normal function, the other for a method.
IMHO this makes no sense at all. Arguable may be for example LHS
ctrs[i], or something like that. But self.ctr ...! Too weird.

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


New assignmens ...

2021-10-22 Thread Paulo da Silva
Hi!

Why doesn't this work
if (self.ctr:=self.ctr-1)<=0:
while this works
if (ctr:=ctr-1)<=0:

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


Re: spyder does not work under root! [linux]

2021-10-14 Thread Paulo da Silva
Às 23:55 de 13/10/21, Michael Torrie escreveu:
> On 10/13/21 12:09 PM, Paulo da Silva wrote:
>> spyder and eric are both python editors/debuggers! Why are they related
>> with web browsers?!
> 
> Good point. I was going off of the chromium bug report. My bad.  I
> mistook Spyder for Selenium, which is a web scraping scripting engine
> that does use a real browser.  Oops.
> 
> However, for better or worse, browser engines power all kinds of apps
> these days, including IDEs. I do not know if Spyder is powered by
> Chromium or not.  VS Code, for example,  is powered by a web browser engine.
> 
> As to Eric and Qt, I can't speak to that.

Software starts to get sickly complicated these days :-(

Thanks Michael and Peter.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: spyder does not work under root! [linux]

2021-10-14 Thread Paulo da Silva
Às 16:16 de 14/10/21, Mats Wichmann escreveu:
> On 10/13/21 16:55, Michael Torrie wrote:
>> On 10/13/21 12:09 PM, Paulo da Silva wrote:
>>> spyder and eric are both python editors/debuggers! Why are they related
>>> with web browsers?!
>>
>> Good point. I was going off of the chromium bug report. My bad.  I
>> mistook Spyder for Selenium, which is a web scraping scripting engine
>> that does use a real browser.  Oops.
>>
>> However, for better or worse, browser engines power all kinds of apps
>> these days, including IDEs. I do not know if Spyder is powered by
>> Chromium or not.  VS Code, for example,  is powered by a web browser
>> engine.
>>
>> As to Eric and Qt, I can't speak to that.
> 
> (sorry sent this wrong place first time)
> 
> 
> The configuration dialog in eric uses its WebBrowser module, which uses
> qtwebengine, which uses Chromium, which gives you the error.  It's not a
> Python error, fwiw.
> 
> It seems there's an environment variable you can try in the Qt world
> (I've never had occasion to check this out):
> 
> https://forum.qt.io/topic/94721/running-as-root-without-no-sandbox-is-not-supported
> 
Ok, thank you.


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


Re: spyder does not work under root! [linux]

2021-10-13 Thread Paulo da Silva
Às 02:08 de 12/10/21, Michael Torrie escreveu:
> On 10/8/21 4:32 PM, Paulo da Silva wrote:
>> Às 22:56 de 08/10/21, Paulo da Silva escreveu:
>>> Hi!
>>>
>>> I need to debug a python3 script under root. I tried spyder but it does
>>> not work.
>>>
>>> Running as root without --no-sandbox is not supported. See
>>> https://crbug.com/638180.
>>>
>>> Thanks for any comments including alternative solutions to debug as root.
>>>
>> I also tried with eric and curiously it gave the same message!!
>>
>> This seems crazy.
> 
> Not so crazy. It's incredibly dangerous to run a web browser as root.
> There's no reason I can think of for running a python script driving a
> web browser as root.
spyder and eric are both python editors/debuggers! Why are they related
with web browsers?!

Thanks

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


Re: spyder does not work under root! [linux]

2021-10-13 Thread Paulo da Silva
Às 22:54 de 11/10/21, Chris Angelico escreveu:
> On Tue, Oct 12, 2021 at 8:52 AM Paulo da Silva
>  wrote:
>>
>> Hi!
>>
>> I need to debug a python3 script under root. I tried spyder but it does
>> not work.
>>
>> Running as root without --no-sandbox is not supported. See
>> https://crbug.com/638180.
>>
>> Thanks for any comments including alternative solutions to debug as root.
>>
> 
> Did you try reading the linked bug report? Or running it with --no-sandbox?
> 
Yes. It is about a web browser! Why are 2 python debuggers related with
a web browser?!
As per spyder, there is no such switch --no-sandbox!

Thanks.

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


Re: Assign a value to a var content in an object

2021-10-11 Thread Paulo da Silva
Às 23:28 de 10/10/21, Stefan Ram escreveu:
> Paulo da Silva  writes:
>> class C:
>>def f(self,v):
>>#setattr(self,n,v)
>>self.__dict__['n']=v
> 
>> Why didn't setattr (as commented) work?
> 
>   Because the name n has not been initialized to a suitable
>   value in the function f. You could write
> 
> setattr( self, "n", v )
Ah, OK - I missed the "" around n! :-(
> 
>   , but if you want this,
> 
> self.n = v
> 
>   would be better.
Of course :-)
But that's not the purpose. This is just a toy example.

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


Assign a value to a var content in an object

2021-10-11 Thread Paulo da Silva
Hello!

Is there a better way of doing this?
Why didn't setattr (as commented) work?

Thanks for an help/comments.

class C:
def f(self,v):
#setattr(self,n,v)
self.__dict__['n']=v

c=C()
c.f(3)
print(c.n)

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


Re: spyder does not work under root! [linux]

2021-10-11 Thread Paulo da Silva
Às 22:56 de 08/10/21, Paulo da Silva escreveu:
> Hi!
> 
> I need to debug a python3 script under root. I tried spyder but it does
> not work.
> 
> Running as root without --no-sandbox is not supported. See
> https://crbug.com/638180.
> 
> Thanks for any comments including alternative solutions to debug as root.
> 
I also tried with eric and curiously it gave the same message!!

This seems crazy.
-- 
https://mail.python.org/mailman/listinfo/python-list


spyder does not work under root! [linux]

2021-10-11 Thread Paulo da Silva
Hi!

I need to debug a python3 script under root. I tried spyder but it does
not work.

Running as root without --no-sandbox is not supported. See
https://crbug.com/638180.

Thanks for any comments including alternative solutions to debug as root.

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


Re: Class and tkinter problem

2021-01-07 Thread Paulo da Silva
Às 20:35 de 07/01/21, Terry Reedy escreveu:
> On 1/7/2021 4:20 AM, Terry Reedy wrote:
>> On 1/7/2021 2:42 AM, Christian Gollwitzer wrote:
>>> Am 07.01.21 um 08:29 schrieb Paulo da Silva:
>>>
>>>> Does anybody know why cmd method isn't called when I change the button
>>>> state (clicking on it) in this example?
>>>> I know that this seems a weird class use. But why doesn't it work?
>>>> Thanks.
>>>>
>>>> class C:
>>>>  from tkinter import Checkbutton
>>>>  import tkinter
>>>>
>>>>  @staticmethod
>>> ^^it works if you remove the staticmethod here
>>
>> staticmethods are essentially useless in Python.  What little was
>> gained by their addition is partly offset by the introduced confusion.
> 
>>>>  def cmd():
>>>>  print("Test")
> 
> The confusion is that methods are callable, whereas 'staticmethods' are
> not.  I was not completely aware of this until pointed out by Peter
> Otten with example
> 
> "    cmd()
> 
> Traceback (most recent call last):
>   File "", line 1, in 
>     class C:
>   File "", line 4, in C
>     cmd()
> TypeError: 'staticmethod' object is not callable
> 
> You have to go through the descriptor protocol:"
> 
> Indeed, dir(cmd) shows that it does not have a .__call__ attribute.
> 
>>  top=tkinter.Tk()
>>  cb=Checkbutton(command=cmd)
> 
>> Button commands have to be tcl functions.  Tkinter wraps Python
>> functions as tcl function.  Static methods also wrap python functions,
>> as a .__func__ attribute.  So the code if one passes cmd.__func__.
> 
> "So the code works if one passes the callable cmd.__func__."
> 
>>> Maybe there is a bug in tkinter, that it doesn't work with static
>>> methods?
>>
>> One could propose that tkinter test whether callables are staticmethods 
> 
> Command options, as documented, must be callables. Neither staticmethods
> nor classmethods are callable.
> 
>> and unwrap them when they are.
> 
>  I would propose instead that if possible tkinter raise TypeError when
> passed a non-callable as a command.
> 
Yes, that would be much better.
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Class and tkinter problem

2021-01-07 Thread Paulo da Silva
Às 07:29 de 07/01/21, Paulo da Silva escreveu:
> Hi!
> 
> Does anybody know why cmd method isn't called when I change the button
> state (clicking on it) in this example?
> I know that this seems a weird class use. But why doesn't it work?
> Thanks.
> 
> class C:
> from tkinter import Checkbutton
> import tkinter
> 
> @staticmethod
> def cmd():
> print("Test")
> 
> top=tkinter.Tk()
> cb=Checkbutton(command=cmd)
> cb.pack()
> 
> @staticmethod
> def loop():
> C.top.mainloop()
> 
> c=C()
> c.loop()
> 

After some experiments I found two solutions:

1)

class C:
@staticmethod
def cmd():
print("Test")
class C: #@DuplicatedSignature
from tkinter import Checkbutton
import tkinter

top=tkinter.Tk()
cb=Checkbutton(command=C.cmd)
cb.pack()

@staticmethod
def loop():
C.top.mainloop()

c=C()
c.loop()

2)

class C:
from tkinter import Checkbutton
import tkinter

@staticmethod
def cmd():
print("Test")

top=tkinter.Tk()
cb=Checkbutton(command=lambda : C.cmd())
cb.pack()

@staticmethod
def loop():
C.top.mainloop()

c=C()
c.loop()

This one as a sequence of the answer of Terry - thanks.

BTW, does anyone know I can I get the arguments eventually passed by the
Checkbutton event, or any other widget callback (*pargs, **kargs) using
this "solution"?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Class and tkinter problem

2021-01-07 Thread Paulo da Silva
Às 16:02 de 07/01/21, Peter Otten escreveu:
> On 07/01/2021 08:42, Christian Gollwitzer wrote:
>> Am 07.01.21 um 08:29 schrieb Paulo da Silva:
>>
...

> 
> I recommend that the OP use a more conventional stye and do the setup
> outside the class or, better, in an instance of the class.
> 
There are lots of possible more conventional ways, of course.
My purpose was only to understand what was wrong.

Thanks anyway.


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


Re: Class and tkinter problem

2021-01-07 Thread Paulo da Silva
Às 09:20 de 07/01/21, Terry Reedy escreveu:
> On 1/7/2021 2:42 AM, Christian Gollwitzer wrote:
>> Am 07.01.21 um 08:29 schrieb Paulo da Silva:
>>
>>> Does anybody know why cmd method isn't called when I change the button
>>> state (clicking on it) in this example?
>>> I know that this seems a weird class use. But why doesn't it work?
>>> Thanks.
>>>
>>> class C:
>>>  from tkinter import Checkbutton
>>>  import tkinter
>>>
>>>  @staticmethod
>> ^^it works if you remove the staticmethod here
> 
> staticmethods are essentially useless in Python.  What little was gained
> by their addition is partly offset by the introduced confusion.
It depends on what the classes are being used for.
Sometimes I just want to use them as static wrappers.
Of course I could use them in the conventional way for this purpose, but
it's not so clean :-)
...

> 
> Classmethods also do not work as is.  By experiment, the following works.
>     cb=Checkbutton(command=lambda: C.cmd.__func__(C))
Why not just
cb=Checkbutton(command=lambda : C.cmd()) ?
Also works.
BTW, just for curiosity, and for my personal learning ... What does
"__func__" does?

Thank you.


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


Re: Class and tkinter problem

2021-01-07 Thread Paulo da Silva
Às 07:42 de 07/01/21, Christian Gollwitzer escreveu:
> Am 07.01.21 um 08:29 schrieb Paulo da Silva:
> 
>> Does anybody know why cmd method isn't called when I change the button
>> state (clicking on it) in this example?
>> I know that this seems a weird class use. But why doesn't it work?
>> Thanks.
>>
>> class C:
>>  from tkinter import Checkbutton
>>  import tkinter
>>
>>  @staticmethod
> ^^it works if you remove the staticmethod here

Yes, that's the coventional way.
Thanks

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


Class and tkinter problem

2021-01-06 Thread Paulo da Silva
Hi!

Does anybody know why cmd method isn't called when I change the button
state (clicking on it) in this example?
I know that this seems a weird class use. But why doesn't it work?
Thanks.

class C:
from tkinter import Checkbutton
import tkinter

@staticmethod
def cmd():
print("Test")

top=tkinter.Tk()
cb=Checkbutton(command=cmd)
cb.pack()

@staticmethod
def loop():
C.top.mainloop()

c=C()
c.loop()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: numpy/python (image) problem

2020-12-09 Thread Paulo da Silva
Às 05:55 de 09/12/20, Paulo da Silva escreveu:
> Hi!
> 
> I am looking at some code, that I found somewhere in the internet, to
> compute DCT for each 8x8 block in an gray (2D) image (512x512).
> 
> This is the code:
> 
> def dct2(a):
> return
> scipy.fft.dct(scipy.fft.dct(a,axis=0,norm='ortho'),axis=1,norm='ortho')
> 
> imsize=im.shape
> dct=np.zeros(imsize)
> 
> # Do 8x8 DCT on image (in-place)
> for i in r_[:imsize[0]:8]: # Seems the same as "for i in
> np.arange(0,imsize[0],8)"!
> for j in r_[:imsize[1]:8]:
> dct[i:(i+8),j:(j+8)]=dct2(im[i:(i+8),j:(j+8)])
> 
> I tried to do the same thing with:
> 
> imsize=im.shape
> im8=im.reshape(imsize[0]*imsize[1]//8//8,8,8)
> dct_test=np.asarray([dct2(im8x) for im8x in im8])
> dct_test=dct_test.reshape(imsize)
> 
> so that dct_test should be equal to (previous) dct.
> But they are completely different.
> 
> What am I doing wrong?
> 
This was silly :-)
The first code splits the image in 8x8 squares.
The last one builds 8x8 squares from each line in sequence!

Forget this please.
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


numpy/python (image) problem

2020-12-08 Thread Paulo da Silva
Hi!

I am looking at some code, that I found somewhere in the internet, to
compute DCT for each 8x8 block in an gray (2D) image (512x512).

This is the code:

def dct2(a):
return
scipy.fft.dct(scipy.fft.dct(a,axis=0,norm='ortho'),axis=1,norm='ortho')

imsize=im.shape
dct=np.zeros(imsize)

# Do 8x8 DCT on image (in-place)
for i in r_[:imsize[0]:8]: # Seems the same as "for i in
np.arange(0,imsize[0],8)"!
for j in r_[:imsize[1]:8]:
dct[i:(i+8),j:(j+8)]=dct2(im[i:(i+8),j:(j+8)])

I tried to do the same thing with:

imsize=im.shape
im8=im.reshape(imsize[0]*imsize[1]//8//8,8,8)
dct_test=np.asarray([dct2(im8x) for im8x in im8])
dct_test=dct_test.reshape(imsize)

so that dct_test should be equal to (previous) dct.
But they are completely different.

What am I doing wrong?

Thanks a lot.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Learning tkinter - a grid problem

2020-12-05 Thread Paulo da Silva
Às 20:20 de 05/12/20, MRAB escreveu:
> On 2020-12-05 18:56, Paulo da Silva wrote:
>> Hi!
>>
>> Why this example does not work?
>>
> There are a few bits of configuration missing:
> 
>> --
>> from tkinter import *
>>
>> root=Tk()
>> root.geometry("400x200")
> 
> Add:
> 
> root.grid_rowconfigure(0, weight=1)
> root.grid_columnconfigure(0, weight=1)
> root.grid_columnconfigure(1, weight=0)
> 
>> S=Scrollbar(root)
>> T=Text(root)
>> T.grid(row=0,column=0)
>> S.grid(row=0,column=1)
> 
> Change to:
> 
> T.grid(row=0, column=0, sticky=NSEW)
> S.grid(row=0, column=1, sticky=NS)
> 
>> S.config(command=T.yview)
>> T.config(yscrollcommand=S.set)
>> txt="""This is a very big text
>> -

Ok, thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Learning tkinter - a grid problem

2020-12-05 Thread Paulo da Silva
Hi!

Why this example does not work?

--
from tkinter import *

root=Tk()
root.geometry("400x200")
S=Scrollbar(root)
T=Text(root)
T.grid(row=0,column=0)
S.grid(row=0,column=1)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
txt="""This is a very big text
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Last line
"""
T.insert(END,txt)
mainloop()
-

I would like it to work more or less like this

-
from tkinter import *

root=Tk()
root.geometry("400x200")
S=Scrollbar(root)
T=Text(root)
S.pack(side=RIGHT,fill=Y)
T.pack(side=LEFT,fill=Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
txt="""This is a very big text
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Last line
"""
T.insert(END,txt)
mainloop()
-

Thanks for any help
Paulo

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


Re: Problem exiting from a script using tkinter

2020-11-25 Thread Paulo da Silva
Às 22:44 de 21/11/20, Chris Angelico escreveu:
> On Sun, Nov 22, 2020 at 9:36 AM Paulo da Silva
>  wrote:
>>
>> Às 22:18 de 21/11/20, Chris Angelico escreveu:
>>> On Sun, Nov 22, 2020 at 9:16 AM Paulo da Silva
>>>  wrote:
>>>>
>>>> Hi!
>>>>
>>>> Why this does not work?!
>>>>
>>>> from tkinter import *
>>>>
>>>> def terminate(root):
>>>> root.quit
>>>>
>>>
>>> Is root.quit a function? Simply referencing a function's name does not
>>> call it (because functions are first-class objects - you can put a
>>> function in a variable or pass it as a parameter etc). In order to
>>> make it do its work, you have to call it.
>>>
>>
>> A newbie Error :-(
>> Sorry. I am giving my first steps in tkinter and I thought it was
>> another problem :-)
>> I just copied the "root.quit" inside the function.
>>
> 
> No need to feel bad about it :) Getting your head around "this is a
> function, that's where the function's being called" is not easy, and
> it takes experience.
> 
> Your question was very well put. You provided a short, compact example
> that showcased the problem you were experiencing. That made it easy to
> answer your question. Keep on asking questions like that, please -
> you're helping yourself and making the mailing list a great place too
> :)

Thank you :-)

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


Re: Problem exiting from a script using tkinter

2020-11-21 Thread Paulo da Silva
Às 22:18 de 21/11/20, Chris Angelico escreveu:
> On Sun, Nov 22, 2020 at 9:16 AM Paulo da Silva
>  wrote:
>>
>> Hi!
>>
>> Why this does not work?!
>>
>> from tkinter import *
>>
>> def terminate(root):
>> root.quit
>>
> 
> Is root.quit a function? Simply referencing a function's name does not
> call it (because functions are first-class objects - you can put a
> function in a variable or pass it as a parameter etc). In order to
> make it do its work, you have to call it.
> 

A newbie Error :-(
Sorry. I am giving my first steps in tkinter and I thought it was
another problem :-)
I just copied the "root.quit" inside the function.

Thanks Chris.

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


Problem exiting from a script using tkinter

2020-11-21 Thread Paulo da Silva
Hi!

Why this does not work?!

from tkinter import *

def terminate(root):
root.quit


root=Tk()
#b=Button(root,text="QUIT",command=root.quit)
b=Button(root,text="QUIT",command=lambda: terminate(root))
b.pack()

mainloop()

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


Re: Like c enumeration in python3

2020-03-23 Thread Paulo da Silva
Thank you very much for all your responses!
Now I have too much ideas :-)
I'm saving your answers and I'll see what is more
appropriate/comfortable in my case.

Best regards.
Paulo
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Like c enumeration in python3 [ERRATA]

2020-03-22 Thread Paulo da Silva
Às 02:18 de 23/03/20, Paulo da Silva escreveu:
> Hi!
> 
> Suppose a class C.
> I want something like this:
> 
> class C:
>   KA=0
>   KB=1
KC=2
>   ...
>   Kn=n
> 
>   def __init__ ...
>   ...
> 
> 
> These constants come from an enum in a .h (header of C file).
> They are many and may change from time to time.
> Is there a way to somehow define them from inside __init__ giving for
> example a list of names as strings?
> There is an additional problem: C is not recognized inside __init__!
Of course I'm talking about C class name, not C language.
> 
> Thanks.
> 

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


Like c enumeration in python3

2020-03-22 Thread Paulo da Silva
Hi!

Suppose a class C.
I want something like this:

class C:
KA=0
KB=1
KC=1
...
Kn=n

def __init__ ...
...


These constants come from an enum in a .h (header of C file).
They are many and may change from time to time.
Is there a way to somehow define them from inside __init__ giving for
example a list of names as strings?
There is an additional problem: C is not recognized inside __init__!

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


Re: super or not super?

2019-07-16 Thread Paulo da Silva
Às 02:11 de 15/07/19, Chris Angelico escreveu:
> On Mon, Jul 15, 2019 at 10:51 AM Paulo da Silva
>  wrote:
>>
...

>>
>> Thank you Jollans. I forgot multiple inheritance. I never needed it in
>> python, so far.
>>
> 
> Something to consider is that super() becomes useful even if someone
> else uses MI involving your class. Using super() ensures that your
> class will play nicely in someone else's hierarchy, not just your own.
> 
Yes, I see. Thanks.

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


Re: super or not super?

2019-07-14 Thread Paulo da Silva
Às 16:20 de 12/07/19, Rhodri James escreveu:
> On 12/07/2019 15:12, Paulo da Silva wrote:


> ...

> super() also has major advantages if you are stuck with multiple
> inheritance.  Raymond Hettinger has an excellent article on this here:
> https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
> 

Thank you. I'll take a look at the suggestion.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: super or not super?

2019-07-14 Thread Paulo da Silva
Às 15:30 de 12/07/19, Thomas Jollans escreveu:
> On 12/07/2019 16.12, Paulo da Silva wrote:
>> Hi all!
>>
>> Is there any difference between using the base class name or super to
>> call __init__ from base class?
> 
> There is, when multiple inheritance is involved. super() can call
> different 'branches' of the inheritance tree if necessary.
> ...

Thank you Jollans. I forgot multiple inheritance. I never needed it in
python, so far.

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


super or not super?

2019-07-12 Thread Paulo da Silva
Hi all!

Is there any difference between using the base class name or super to
call __init__ from base class?

class C1:
def __init__(self):
...

class C2(C1):
def __init__(self):
C1.__init__(self) or super().__init__() ??
...

I have been using super, but I see some scripts where the base class
name is used.

Thanks for any comments.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dataframe with two groups of cols. [RESOLVED]

2019-06-14 Thread Paulo da Silva
Às 18:31 de 14/06/19, Paulo da Silva escreveu:
> Às 04:56 de 14/06/19, Paulo da Silva escreveu:
...


> 
> After digging a lot :-) , and for those who may be interested, I found
> one way:
> 
> In [21]: d1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8,
> 9]]),columns=['C1', 'C2', 'C3'])
> 
> In [22]: d2 = pd.DataFrame(np.array([[10, 2, 3], [10, 5, 6], [10, 8,
> 9]]),columns=['C1', 'C2', 'C3'])
> 
> In [23]: d=pd.concat([d1,d2],keys=['G1','G2'],axis=1)
> 
> In [24]: d
> Out[24]:
>   G1G2
>   C1 C2 C3  C1 C2 C3
> 0  1  2  3  10  2  3
> 1  4  5  6  10  5  6
> 2  7  8  9  10  8  9
> 
> In [25]: d['G2']['C1']
> Out[25]:
> 010
> 110
> 210
> Name: C1, dtype: int64
> 
> In [26]:
> 

And I noticed that things are yet more flexible ...
For ex. we can add further data

In [12]: d['G3','C1']=['v1','v2','v3']

In [13]: d
Out[13]:
  G1G2G3
  C1 C2 C3  C1 C2 C3  C1
0  1  2  3  10  2  3  v1
1  4  5  6  10  5  6  v2
2  7  8  9  10  8  9  v3

... but starting with an empty dataframe does not work!
In [3]: df=pd.DataFrame()

In [4]: df['G1','c1']=[1,2,3]

In [5]: df
Out[5]:
   (G1, c1)
0 1
1 2
2 3

In [6]:

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


Re: Dataframe with two groups of cols. [RESOLVED]

2019-06-14 Thread Paulo da Silva
Às 04:56 de 14/06/19, Paulo da Silva escreveu:
> Hi!
> 
> How do I create a pandas dataframe with two (or more) groups of cols.?
> 
> Ex.:
> 
> G1   G2
> C1 C2 C3 C1 C2 C3
> Rows of values ...
> 
> I then should be able to access for example
> df['G2']['C3'][]
> 
> 
> Thanks.
> 

After digging a lot :-) , and for those who may be interested, I found
one way:

In [21]: d1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8,
9]]),columns=['C1', 'C2', 'C3'])

In [22]: d2 = pd.DataFrame(np.array([[10, 2, 3], [10, 5, 6], [10, 8,
9]]),columns=['C1', 'C2', 'C3'])

In [23]: d=pd.concat([d1,d2],keys=['G1','G2'],axis=1)

In [24]: d
Out[24]:
  G1G2
  C1 C2 C3  C1 C2 C3
0  1  2  3  10  2  3
1  4  5  6  10  5  6
2  7  8  9  10  8  9

In [25]: d['G2']['C1']
Out[25]:
010
110
210
Name: C1, dtype: int64

In [26]:
-- 
https://mail.python.org/mailman/listinfo/python-list


Dataframe with two groups of cols.

2019-06-13 Thread Paulo da Silva
Hi!

How do I create a pandas dataframe with two (or more) groups of cols.?

Ex.:

G1   G2
C1 C2 C3 C1 C2 C3
Rows of values ...

I then should be able to access for example
df['G2']['C3'][]


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


Re: Better ways for implementing two situations

2019-04-23 Thread Paulo da Silva
Às 22:21 de 21/04/19, Paul Rubin escreveu:
> Paulo da Silva  writes:
>> splitter={}
>> for f in Objs:
>>  splitter.setdefault(f.getId1,[]).append(f)
>> groups=[gs for gs in splitter.values() if len(gs)>1]
> 
> It's easiest if you can sort the input list and then use
> itertools.groupby.
Yes, sort and groupby seems the best way to go.
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Better ways for implementing two situations

2019-04-23 Thread Paulo da Silva
Às 20:41 de 21/04/19, DL Neil escreveu:
> Olá Paulo,
> 
...


> 
> Given that we're talking "big data", which Python Data Science tools are
> you employing? eg NumPy.
Sorry. I misused the term "big data". I should have said a big amount of
data. It is all about objects built of text and some numbers. Some
properties of some objects are got on demand and when needed by reading
and processing data from the hard drive.

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


Re: Better ways for implementing two situations

2019-04-23 Thread Paulo da Silva
Às 20:10 de 21/04/19, MRAB escreveu:
> On 2019-04-21 19:23, Paulo da Silva wrote:
>> Hi all.
>>
...
> Have you compared the speed with an implementation that uses
> defaultdict? Your code always creates an empty list for each item, even
> though it might not be needed.

I never used defaultdict. I'll take a look at it.
Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Better ways for implementing two situations

2019-04-23 Thread Paulo da Silva
Às 19:42 de 21/04/19, Stefan Ram escreveu:
> Paulo da Silva writes:
>> I have a list of objects and want to split it in a list of groups.
>> "equal objects" is based on an id we can get from the object.
> 
>   main.py
> 
> input = [ 'abc', 'ade', 'bcd' ]
> 
> for group, list in \
> __import__( 'itertools' ).groupby( input, lambda x: x[ 0 ] ):
> print( group, *list )
> 

Yes, seems to be the best way to go. I need to sort data first, however.

Thanks

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


Better ways for implementing two situations

2019-04-21 Thread Paulo da Silva
Hi all.

I am looking for improved solutions to these two problems.
They are to be in a program that deals with big data. So, they need to
be fast and save memory.

Problem 1.

I have a list of objects and want to split it in a list of groups.
Each group must have all "equal objects" and have more than one object.
"equal objects" is based on an id we can get from the object.
Nothing is sorted.

Here is my implementation:

splitter={}
for f in Objs:
splitter.setdefault(f.getId1,[]).append(f)
groups=[gs for gs in splitter.values() if len(gs)>1]


Problem 2.

I know it seems confusing but pls. look at the implementation.
Here I have a list of lists of objects - groups.
Now let's say l is a given list from groups, containing objects.
I want to replace this list l with a new list of sublists where each
sublist is a list of "equal objects".
The new l must have more than one list.
The final result is a list of lists of lists.
Nothing is sorted.

Here is my implementation:

gs=[]
for g in groups:
splitter={}
for f in g:
splitter.setdefault(f.getId2(),[]).append(f)
gse=list(splitter.values())
if len(gse)>1: gs.append(gse)

gs is the result.

Thanks for any comments.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting file extensions [linux fs]

2019-04-08 Thread Paulo da Silva
Às 01:35 de 06/04/19, Pablo Lucena escreveu:
> Have you looked into eBPF?
I'll take a look at that. Thanks Pablo.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Getting file extensions [linux fs]

2019-03-30 Thread Paulo da Silva
Às 22:18 de 28/03/19, Cameron Simpson escreveu:
> On 28Mar2019 01:12, Paulo da Silva  wrote:
>> Às 23:09 de 27/03/19, Cameron Simpson escreveu:
...

> 
> Oh, just tangential to this.
> 
> If you were doing this ad hoc, yes calling the filefrag executable is
> very expensive. But if you are always doing a large batch of filenames
> invoking:
> 
>  filefrag lots of filenames here ...>
> and reading from its output can be very effective, because the expense
> of the executable is amortized over all the files - the per file cost is
> much reduced. And it saves you working out how to use the ioctls from
> Python :-)
That's not the case.
I need to do it on some files basis which I don't know in advance.
Using IOCTL, I don't need to parse or unpack the output. Only compare
the output arrays. Besides I need to store many of the outputs. Doing
that from filefrag text output would be unpractical. I needed, at least,
to compress the data. Although may be I might have to compress the ioctl
arrays ... Let's see how big in average is the storage needed.

I have to go with ioctl. I have to open the files anyway, so there is no
overhead for that when calling the ioctl.

Anyway, thank you for the suggestion.

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


Re: Getting file extensions [linux fs]

2019-03-27 Thread Paulo da Silva
Às 23:09 de 27/03/19, Cameron Simpson escreveu:
> On 27Mar2019 21:49, Paulo da Silva  wrote:
...
> The filefrag manual entry says it works by calling one of 2 ioctls. You
> can do that from Python with the ioctl() function in the standard fcntl
> module. I haven't tried to do this, but the results should be basicly as
> fast as filefrag itself.
> 
> You'll need to decode the result the ioctl returns of course.
> 
Thanks Cameron, I'll take a look at that.
-- 
https://mail.python.org/mailman/listinfo/python-list


Getting file extensions [linux fs]

2019-03-27 Thread Paulo da Silva
Hi!

I don't know if this is the right group to ask ... sorry if it isn't.

Is there a way to get the file extensions of a file in linux, the same
way as "filefrag -e " does?

The purpose is to see if two files are the same file, namely those
copied with the --reflink option in btrfs.

A solution for C is also welcome - I can write a small python extension
to handle that.

BTW, executing filefrag from python is not a solution, because I have
lots of files and that would be too slow.

Thanks for any help. Anyway, as last resource, I can always look at
filefrag source. I am just trying to avoid that.

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


Re: conda/anaconda and pip3 (pip)

2019-01-05 Thread Paulo da Silva
Às 17:39 de 03/12/18, Paulo da Silva escreveu:

Well ... further clarification ...

> Hi!
> 
> I have an environment created with conda (anaconda3).
> There is a package that is unavailable in conda.
The package is sklearn (import sklearn). - Look below before comment pls.

> Installing it with pip3, with conda env activated, the installation goes
> to .local/bin and .local/lib in my home dir (BTW I'm running linux
> kubuntu 18.04).
This is because I used pip3.
pip3 is from the system.
Inside conda MyPy (my conda environment) only pip is available. This
"pip" works with python3.

So:
- I uninstalled sklearn using pip3 and installed it with pip.
- This sucessfully installed sklearn (a very small bunch of small files).
import sklearn didn't work!

I uninstalled sklearn with pip.

Then I searched for sklearn from the top level of anaconda3 dir.
I find few of them, all global to anaconda3 but out of the environment.
This means that these packages are not seen from the environment.
Besides sklearn was inside the scikit-learn package.

So I activated MyPy (my environment) and did
conda install scikit-learn

Now everything is working and coherent.

Still confused, however ...

Thank you all.
Regards.

--- news://freenews.netfront.net/ - complaints: n...@netfront.net ---
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: conda/anaconda and pip3 (pip)

2019-01-04 Thread Paulo da Silva
Às 19:39 de 02/01/19, Hartmut Goebel escreveu:
> Am 03.12.18 um 18:39 schrieb Paulo da Silva:
>> This also has a bad side effect! It reinstalls there some depedencies
>> already installed in the conda created environment!
>>
>> Is there a way to avoid this situation?
> 
> Try whether  `pyvenv --system-site-packages` suites you.
> 

I need to use conda for this.
I need anaconda because it has all stuff to work with GPUs. Otherwise
I'd need to install lots of SW. One package, for example, requires
registration at Nvidia. It also difficult to determine a common base of
compatible versions.

Thanks for responding.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: conda/anaconda and pip3 (pip)

2019-01-04 Thread Paulo da Silva
Às 19:54 de 09/12/18, Tim Williams escreveu:
> On Saturday, December 8, 2018 at 10:13:14 PM UTC-5, Monte Milanuk wrote:
>> Did you find any solution(s)?
> 
> I usually just lurk and read on this list. I don't reply since there's 
> usually more competent people that regularly post helpful answers. (I lurk to 
> learn from them!)
> 
> If no one's replied yet, I'll give it my 2 cents ...
> 
> Without being a pip expert, I see from 'pip install -h' that you can specify 
> where you want the package to be installed.
> 
> Install Options:
...

>   path or a VCS url.
>   -t, --target   Install packages into . By default this 
> will not replace existing files/folders in
>   . Use --upgrade to replace existing 
> packages in  with new versions.
...

> 
> I'm thinking the the --target option may be the solution.
> 

I don't think this is a solution.
It seems that there is no really solutions at all.
(ana)conda has its own dependencies management. Playing with pip just
seems to cause dependencies problems, eventually.
So far, I have not found any problems, probably because the newer
modules are backwards compatible.

Thanks for responding.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: cython3: Cannot start!

2018-12-24 Thread Paulo da Silva
Às 14:07 de 24/12/18, Stefan Behnel escreveu:
> Paulo da Silva schrieb am 22.12.18 um 19:26:
...

> 
> Ubuntu 18.04 ships Cython 0.26, which has a funny bug that you hit above.
> It switches the language-level too late, so that the first token (or word)
> in the file is parsed with Py2 syntax. In your case, that's the print
> statement, which is really parsed as (Py2) statement here, not as (Py3)
> function. In normal cases, the language level does not matter for the first
> statement in the source (because, why would you have a print() there?), so
> it took us a while to find this bug.
> 
> pip-installing Cython will get you the latest release, where this bug is
> resolved.
> 

Thank you Stefan for the clarification.
Regards.
Paulo

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


Re: cython3: Cannot start! [RESOLVED]

2018-12-22 Thread Paulo da Silva
Às 19:48 de 22/12/18, MRAB escreveu:
> On 2018-12-22 18:26, Paulo da Silva wrote:
...


> Well, I've just tried this on Raspbian with the same files (for Python 3):
> 
> python3 -m pip install cython
> python3 setup.py build_ext --inplace
> python3 -c 'import tp'
> 
> and it printed:
> 
> Test 2

OK. I uninstalled the distributed cython3 and installed it using pip3.
Now it works!

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


cython3: Cannot start!

2018-12-22 Thread Paulo da Silva
Hi!
Sorry if this is OT.

I decided to give cython a try and cannot run a very simple program!

1. I am using kubuntu 18.04 and installe cython3 (not cython).

2. My program tp.pyx:

# cython: language_level=3
print("Test",2)

3. setup.py
from distutils.core import setup
from Cython.Build import cythonize

setup(
ext_modules = cythonize("tp.pyx")
)

4. Running it:
python3 setup.py build_ext --inplace
python3 -c 'import tp'

5. output:
('Test', 2)

This is wrong for python3! It should output
Test 2

It seems that it is parsing tp.pyx as a python2 script!

I tried to change the print to python2
print "Test",2

and it recognizes the syntax and outputs
Test 2

So, how can I tell cython to use python3?

Thanks for any help/comments
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why Python don't accept 03 as a number?

2018-12-07 Thread Paulo da Silva
Às 01:17 de 08/12/18, jf...@ms4.hinet.net escreveu:
 00
> 0
 03
>   File "", line 1
> 03
>  ^
> SyntaxError: invalid token

> 
> Any particular reason?
> 

Not sure but I think that after 0 it expects x for hexadecimal, o for
octal, b for binary, ... may be others.

0xa
10

0o10
8

0b10
2
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tkinter resizable text with grid

2018-12-07 Thread Paulo da Silva
Às 07:11 de 07/12/18, Christian Gollwitzer escreveu:
> Am 07.12.18 um 03:00 schrieb Paulo da Silva:
>> Às 21:15 de 06/12/18, Rick Johnson escreveu: 
...

> So instead of complaining about lacking support in Tk, the
> Python community should do their homework and provide wrappers to the
> most common Tk extensions.
> 

That was what I did. When I referred tk was in the context of python.
I left tcl/tk long time ago and by that time the problems were the same
as tkinter's today, not to mention the angels sex discussions/wars about
which oop paradigm to use or if use any at all :-)

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


Re: tkinter resizable text with grid

2018-12-06 Thread Paulo da Silva
Às 21:15 de 06/12/18, Rick Johnson escreveu:
> Paulo da Silva wrote:
> 
...

> 
> In Tkinter, if you have a "container"[1] that only has a
> single widget stuffed inside, and, you want that single
> widget to expand to fill the extents of its parent
> container, then, the pack geometry manager is the simplest
> approach.
> 
> w = create_a_widget()
> w.pack(fill=X|Y|BOTH, expand=YES)
Yes, I am aware of pack. Unfortunately the code fragment I posted is a
very small part of a larger widget.

...

> 
> I kinda have a love/hate relationship with Tkinter and IDLE.
> On one hand i find them to be practical[2] and simple[3] and
> on the other, i find them to be poorly designed and
> unintuitive. And it's a real shame, because, both of these
> libraries have tons of potential, *IF*, they were designed
> probably and the shortcomings of TclTk were abstracted away
> behind a more Pythonic interface.
> 

I fully agree. Nevertheless, what I miss more is the lack of more
complex mega widgets - scrollable list of widgets with insert, append
and remove methods and perhaps a spreadsheet like widget are two big
ones. There are others smaller, like a single scrollable text with two
scroll bars that hide when not needed, tab multi-choice container, etc ...

Unfortunately I rarely need gui programming and don't have the expertise
to address such task. Being tk so old, I wonder why no one developed
those expansions - continuing tix, for example. There are some
implementations but they seem not being maintained.

Pmw has some of the later, but it is not much stable for python3.

Thanks for responding
Paulo
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tkinter resizable text with grid

2018-12-06 Thread Paulo da Silva
Às 08:24 de 06/12/18, Peter Otten escreveu:
> Paulo da Silva wrote:
> 
...
> 
> You have to set the column/row weight of the /master/:
> 
>   master.grid_columnconfigure(1, weight=1)
>   master.grid_rowconfigure(1, weight=1)
Ok. That works!


> 
> Also, columns and rows usually start with 0.
>  
Yes, I know that. I have other stuff there.

Thank you very much Peter.
-- 
https://mail.python.org/mailman/listinfo/python-list


tkinter resizable text with grid

2018-12-05 Thread Paulo da Silva
Hi!

Does anybody know why this code does not expand the text widget when I
increase the window size (with mouse)? I want height and width but as
minimum (or may be initial) size.

import tkinter as tk

class App:
def __init__(self,master):
self.tboard=tk.Text(master,height=40,width=50)
self.tboard.grid(row=1,column=1,sticky="nsew")
self.tboard.grid_rowconfigure(1,weight=1)
self.tboard.grid_columnconfigure(1,weight=1)

root=tk.Tk()
app=App(root)

root.mainloop()

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


conda/anaconda and pip3 (pip)

2018-12-03 Thread Paulo da Silva
Hi!

I have an environment created with conda (anaconda3).
There is a package that is unavailable in conda.
Installing it with pip3, with conda env activated, the installation goes
to .local/bin and .local/lib in my home dir (BTW I'm running linux
kubuntu 18.04).
This also has a bad side effect! It reinstalls there some depedencies
already installed in the conda created environment!

Is there a way to avoid this situation?

Thanks for any help.
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   >