Verify pip's requirements.txt file at runtime?

2018-09-11 Thread Malcolm Greene
Is there a technique that would allow a script to verify its
requirements.txt file before it runs? Use case: To detect unexpected
changes to a script's runtime environment. Does the pip module expose
any methods for this type of task?
Thank you,
Malcolm
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Object-oriented philosophy

2018-09-11 Thread Antoon Pardon
On 07-09-18 22:08, Michael F. Stemper wrote:
>
>>  try
>>id = xmlmodel.attrib['name']
>>  except KeyError:
>>id = "constant power"
> Never mind! After I continued testing, I realized that the above
> should have been written as:
>
>   if 'name' in xmlmodel.attrib:
> id = xmlmodel.attrib['name']
>   else:
> id = "constant power"
>
> 

How about:

id = xmlmodel.attrib.get('name', "constant power")


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


Pretty printing dicts with compact=True

2018-09-11 Thread Nicolas Hug
Is there a reason why the 'compact' parameter is ignored when pretty 
printing a dict? For example:


pprint({x: x for x in range(15)}, compact=True)

would be be printed in 15 lines while it could fit on 2.


Is this a bug or was this decided on purpose?

Thank you!

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


Re: Object-oriented philosophy

2018-09-11 Thread Marko Rauhamaa
Rick Johnson :

> Michael F. Stemper wrote:
>> Object-oriented philosophy
> [...] [...] [...]
>
> So, to make a long story short, you may want to do some
> googling...

Long story short, Michael, Rick is a masterful troll extraordinaire.
Highly amusing when you're in the mood.


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


Re: Object-oriented philosophy

2018-09-11 Thread Michael F. Stemper
On 2018-09-11 01:59, Marko Rauhamaa wrote:
> Rick Johnson :
> 
>> Michael F. Stemper wrote:
>>> Object-oriented philosophy
>> [...] [...] [...]
>>
>> So, to make a long story short, you may want to do some
>> googling...
> 
> Long story short, Michael, Rick is a masterful troll extraordinaire.

Is that why he misquoted "Big Yellow Taxi"? (Hint: a song with "raped"
in it would not have had any air time in 1970.)

> Highly amusing when you're in the mood.

Incoherent, too.

-- 
Michael F. Stemper
Galatians 3:28
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Object-oriented philosophy

2018-09-11 Thread Abdur-Rahmaan Janhangeer
i did not see rick's mail on my gmail

Abdur-Rahmaan Janhangeer
https://github.com/Abdur-rahmaanJ
Mauritius


Rick Johnson :
>
> > Michael F. Stemper wrote:
> >> Object-oriented philosophy
> > [...] [...] [...]
> >
> > So, to make a long story short, you may want to do some
> > googling...
>
> Long story short, Michael, Rick is a masterful troll extraordinaire.
> Highly amusing when you're in the mood.
>
>
> Marko
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pretty printing dicts with compact=True

2018-09-11 Thread Max Zettlmeißl via Python-list
On Tue, Sep 11, 2018 at 1:58 PM, Nicolas Hug  wrote:
> pprint({x: x for x in range(15)}, compact=True)
>
> would be be printed in 15 lines while it could fit on 2.
>
>
> Is this a bug or was this decided on purpose?

It is on purpose as can be seen in the code for pprint [1], which
calls _format [2], which in the case of a dictionary calls
_pprint_dict [3], which ultimately calls _format_dict_items [4].
(which does not use compact or rather _compact)

To me it also seems to be the most sensible behaviour, since
dictionaries with their keys and values are different from most other
sequences. In a dictionary the relation between keys and values is the
most important one and reading a dictionary certainly is easier if
each key value pair has a line of it's own. (Especially if the keys
and values vary a lot in their lengths.)

[1] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L138
[2] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L154
[3] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L180
[4] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L333
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Object-oriented philosophy

2018-09-11 Thread Abdur-Rahmaan Janhangeer
i know about the ban but since marko was getting it was wondering how

thanks !

Abdur-Rahmaan Janhangeer
https://github.com/Abdur-rahmaanJ
Mauritius

Ranting Rick is banned from posting to python-list. (And maybe also
> from other Python project lists, I'm not sure about that.)
> You can read about further details in the topic "Users banned".
>
> You should only see his messages if you read the Newsgroup or if
> someone quotes a message that Rick has posted on the Newsgroup, since
> the Newsgroup is unmoderated.
>
-- 
https://mail.python.org/mailman/listinfo/python-list


numpy use cases for where and out

2018-09-11 Thread duncan smith
Hello,
  I'm writing some code for sparse arrays that is intended to pretty
much follow the numpy API. Because my arrays can have different default
values there is an issue with using the 'out' keyword argument for
functions. e.g. If I elementwise multiply 2 arrays with defaults a and
b, then the default of the product becomes a*b. Changing the default of
'out' to a*b (if that is not the existing default) requires pre-existing
values in 'out' equal to the previous default to be filled in. It seems
to be more hassle than it's worth, and basically eliminates sparsity.

So I am wondering if there are any compelling use cases for 'out'. At
the same time, I'm wondering about 'where'. It's less of an issue. But
given my dictionary of keys implementation, and returning new arrays
rather than views, I'm wondering if I could reasonably eliminate both. I
don't think I've ever used either argument when using numpy. So I'm
asking here in case there are use cases I've overlooked. TIA.

Duncan

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


Re: logging module - how to include method's class name when using %(funcName)

2018-09-11 Thread Peter Otten
Malcolm Greene wrote:

> I'm using the Python logging module and looking for a way to include a
> method's class name when using %(funcName). Is this possible? When you
> have several related classes, just getting the function (method) name is
> not enough information to provide context on the code being executed.
> I'm outputting module name and line number so I can always go back and
> double check a caller's location in source, but that seems like an
> archaic way to find this type of information.

In the code below I took the same approach, but automated it with pyclbr.
While I'm not really happy with the result (is inspect or ast more suitable, 
should Logger be subclassed or adapted rather than specifying the LogRecord 
factory, can the class be determined lazily) here's the current state of 
things:

$ cat findclass.py
def ham(): log.warning("inside ham function")
import bisect
import pyclbr
import logging

LogRecord = logging.LogRecord


class Module:
def __init__(self, module):
mod = pyclbr.readmodule_ex(module)
line2func = []

for classname, cls in mod.items():
if isinstance(cls, pyclbr.Function):
line2func.append((cls.lineno, "", cls.name))
else:
for methodname, start in cls.methods.items():
line2func.append((start, classname, methodname))

line2func.sort()
keys = [item[0] for item in line2func]
self.line2func = line2func
self.keys = keys

def line_to_class(self, lineno):
index = bisect.bisect(self.keys, lineno) - 1
return self.line2func[index][1]


def lookup_module(module):
return Module(module)


def lookup_class(module, funcname, lineno):
if funcname == "":
return ""

module = lookup_module(module)
return module.line_to_class(lineno)


def makeLogRecord(*args, **kw):
record = LogRecord(*args, **kw)
record.className = lookup_class(
record.module, record.funcName, record.lineno
)
if record.className != "":
record.funcName = "{}.{}".format(record.className, record.funcName)
return record


logging.setLogRecordFactory(makeLogRecord)

logging.basicConfig(
format=logging.BASIC_FORMAT
+ " class=%(className)s func=%(funcName)s lineno=%(lineno)s"
)

log = logging.getLogger()
log.warning("module-level")


def foo():
log.warning("inside foo function")
def bar(): log.warning("inside bar function")


class A:
def foo(self):
log.warning("inside A.foo method")


class B:
def foo(self):
log.warning("inside B.foo method")
A().foo()
B().foo()
foo()
bar()
ham()
$ python3.7 findclass.py
WARNING:root:module-level class= func= lineno=61
WARNING:root:inside A.foo method class=A func=A.foo lineno=71
WARNING:root:inside B.foo method class=B func=B.foo lineno=76
WARNING:root:inside foo function class= func=foo lineno=65
WARNING:root:inside bar function class= func=bar lineno=66
WARNING:root:inside ham function class= func=ham lineno=1


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


Re: Pretty printing dicts with compact=True

2018-09-11 Thread Nicolas Hug

To me it also seems to be the most sensible behaviour, since
dictionaries with their keys and values are different from most other
sequences.

You've got a point but

1. That goes against the compact=True expected behaviour

2. Small dicts (e.g. /{x: x for x in range(5)}/) are still printed on a 
single line (regardless of the compact parameter), so I don't believe 
that was the rationale behind this behaviour.



On 9/11/18 1:05 PM, Max Zettlmeißl wrote:

On Tue, Sep 11, 2018 at 1:58 PM, Nicolas Hug  wrote:

pprint({x: x for x in range(15)}, compact=True)

would be be printed in 15 lines while it could fit on 2.


Is this a bug or was this decided on purpose?

It is on purpose as can be seen in the code for pprint [1], which
calls _format [2], which in the case of a dictionary calls
_pprint_dict [3], which ultimately calls _format_dict_items [4].
(which does not use compact or rather _compact)

To me it also seems to be the most sensible behaviour, since
dictionaries with their keys and values are different from most other
sequences. In a dictionary the relation between keys and values is the
most important one and reading a dictionary certainly is easier if
each key value pair has a line of it's own. (Especially if the keys
and values vary a lot in their lengths.)

[1] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L138
[2] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L154
[3] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L180
[4] 
https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L333

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


Python Probability

2018-09-11 Thread Bat erdene endzis
Hello,

I am new to Python and I have an exercise which I struggle with.

The question is:
In the strategic board game called Risk, one player can attack up to three 
soldiers simultaneously, while the defending player can defend up to two. In 
the case of exactly three attackers and two defenders, the collision is as 
follows. An attacking player rolls three red dice while the defending player 
rolls two blue dice. Then they compare the bigest throws of the attacker and 
the defender. The lesser value loses a soldier, in the case of equal values the 
attacker loses one soldier. Then the second largest numbers are also compared 
in the same way. Thus, the battle has three outcomes: the attacker loses two 
soldiers, each side loses 1-1 soldiers, the defender loses two soldiers.
Simulate 1000 times the experiment and determine the relative frequency 
of the three events.Simulate 100 times the experiment and determine the 
relative frequency of the three events.Calculate the exact probability of the 
three outcomes by examining all possible cases. The probability is the ratio of 
the favorable cases and the total number of cases. Write these results with 5 
decimal places leaving 3 spaces between them! The output of the program looks 
like this (of course with other numbers)


Attacker  Draw  Defender
1000 experiment 0.35222   0.4   0.20334
100 experiment  0.33988   0.43011   0.23001
Probability 0.34000   0.43000   0.23000



The aim of this task is to get acquainted with the classical probability field, 
the relative frequency and the relation of it to the probability.Programming 
goal: recalling the basic elements of Python programming and generating random 
numbers.Help: by loading the random package (import random) and calling 
random.random() one may get a random number between 0 and 1 (by uniform 
distribution). The code int(random.random()*6)+1 gives back an integer number 
between 1 and 6.

So I did like:
import random

def dice():
    attacker_dice=[random.randint(1,6) for _ in range(3)]
    defender_dice=[random.randint(1,6) for _ in range(2)]
    a=max(attacker_dice)
    b=max(defender_dice)
    for i in range(1000):
        F=0
        S=0
        T=0
        if a>b:
            F+=1
        if a==b:
            S+=1
        else:
            T+=1
and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me 
zeros or 333. And to get 5digits after the zero i wanted to use "%.5f " %First. 

Could you help me to finish this, and tell me what am I doing wrong?

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


Re: Python Probability

2018-09-11 Thread Peter Pearson
On Tue, 11 Sep 2018 20:54:23 +0200 (CEST), Bat erdene endzis wrote:
[snip]
> def dice():
> attacker_dice=[random.randint(1,6) for _ in range(3)]
> defender_dice=[random.randint(1,6) for _ in range(2)]
> a=max(attacker_dice)
> b=max(defender_dice)
> for i in range(1000):
> F=0
> S=0
> T=0
> if a>b:
> F+=1
> if a==b:
> S+=1
> else:
> T+=1

Do you really want to set F, S, and T back to zero on each pass through
that loop?

Presumably you want to remove a from attacker_dice and b from
defender_dicce and repeat the comparison with the new maxes.

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Probability

2018-09-11 Thread Gary Herron

On 09/11/2018 11:54 AM, [email protected] wrote:

Hello,

I am new to Python and I have an exercise which I struggle with.

The question is:
In the strategic board game called Risk, one player can attack up to three 
soldiers simultaneously, while the defending player can defend up to two. In 
the case of exactly three attackers and two defenders, the collision is as 
follows. An attacking player rolls three red dice while the defending player 
rolls two blue dice. Then they compare the bigest throws of the attacker and 
the defender. The lesser value loses a soldier, in the case of equal values the 
attacker loses one soldier. Then the second largest numbers are also compared 
in the same way. Thus, the battle has three outcomes: the attacker loses two 
soldiers, each side loses 1-1 soldiers, the defender loses two soldiers.
Simulate 1000 times the experiment and determine the relative frequency 
of the three events.Simulate 100 times the experiment and determine the 
relative frequency of the three events.Calculate the exact probability of the 
three outcomes by examining all possible cases. The probability is the ratio of 
the favorable cases and the total number of cases. Write these results with 5 
decimal places leaving 3 spaces between them! The output of the program looks 
like this (of course with other numbers)


 Attacker  Draw  Defender
1000 experiment 0.35222   0.4   0.20334
100 experiment  0.33988   0.43011   0.23001
Probability 0.34000   0.43000   0.23000



The aim of this task is to get acquainted with the classical probability field, 
the relative frequency and the relation of it to the probability.Programming 
goal: recalling the basic elements of Python programming and generating random 
numbers.Help: by loading the random package (import random) and calling 
random.random() one may get a random number between 0 and 1 (by uniform 
distribution). The code int(random.random()*6)+1 gives back an integer number 
between 1 and 6.

So I did like:
import random

def dice():
     attacker_dice=[random.randint(1,6) for _ in range(3)]
     defender_dice=[random.randint(1,6) for _ in range(2)]
     a=max(attacker_dice)
     b=max(defender_dice)
     for i in range(1000):
         F=0
         S=0
         T=0
         if a>b:
             F+=1
         if a==b:
             S+=1
         else:
             T+=1


Every time through this loop, you set F, S and T to zero.  If you want 
those variables to accumulate values, move the three initialization 
lines to before the loop:

F = 0
S = 0
T = 0
for ...
   if a>b:
 F += 1
   ... and so on ...

But you have another problem.  You simulate rolling the dice only once.  
For your 1000 trials, you need to roll the dice 1000 times. The first 
few lines that simulate the dice roll must be inside the loop so that 
each pass through the loop rolls the dice.




and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 
333. And to get 5digits after the zero i wanted to use "%.5f " %First.

Could you help me to finish this, and tell me what am I doing wrong?

Thank you



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


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


Re: Python Probability

2018-09-11 Thread Gary Herron

On 09/11/2018 11:54 AM, [email protected] wrote:

Hello,

I am new to Python and I have an exercise which I struggle with.

The question is:
In the strategic board game called Risk, one player can attack up to three 
soldiers simultaneously, while the defending player can defend up to two. In 
the case of exactly three attackers and two defenders, the collision is as 
follows. An attacking player rolls three red dice while the defending player 
rolls two blue dice. Then they compare the bigest throws of the attacker and 
the defender. The lesser value loses a soldier, in the case of equal values the 
attacker loses one soldier. Then the second largest numbers are also compared 
in the same way. Thus, the battle has three outcomes: the attacker loses two 
soldiers, each side loses 1-1 soldiers, the defender loses two soldiers.
Simulate 1000 times the experiment and determine the relative frequency 
of the three events.Simulate 100 times the experiment and determine the 
relative frequency of the three events.Calculate the exact probability of the 
three outcomes by examining all possible cases. The probability is the ratio of 
the favorable cases and the total number of cases. Write these results with 5 
decimal places leaving 3 spaces between them! The output of the program looks 
like this (of course with other numbers)


 Attacker  Draw  Defender
1000 experiment 0.35222   0.4   0.20334
100 experiment  0.33988   0.43011   0.23001
Probability 0.34000   0.43000   0.23000



The aim of this task is to get acquainted with the classical probability field, 
the relative frequency and the relation of it to the probability.Programming 
goal: recalling the basic elements of Python programming and generating random 
numbers.Help: by loading the random package (import random) and calling 
random.random() one may get a random number between 0 and 1 (by uniform 
distribution). The code int(random.random()*6)+1 gives back an integer number 
between 1 and 6.

So I did like:
import random

def dice():
     attacker_dice=[random.randint(1,6) for _ in range(3)]
     defender_dice=[random.randint(1,6) for _ in range(2)]
     a=max(attacker_dice)
     b=max(defender_dice)
     for i in range(1000):
         F=0
         S=0
         T=0
         if a>b:
             F+=1
         if a==b:
             S+=1
         else:
             T+=1


Every time through this loop, you set F, S and T to zero.  If you want 
those variables to accumulate values, move the three initialization 
lines to before the loop:

F = 0
S = 0
T = 0
for ...
   if a>b:
 F += 1
   ... and so on ...

But you have another problem.  You simulate rolling the dice only once.  
For your 1000 trials, you need to roll the dice 1000 times. The first 
few lines that simulate the dice roll must be inside the loop so that 
each pass through the loop rolls the dice.






and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 
333. And to get 5digits after the zero i wanted to use "%.5f " %First.

Could you help me to finish this, and tell me what am I doing wrong?

Thank you



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


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


Re: "glob.glob('weirdness')" Any thoughts?

2018-09-11 Thread Dan Sommers

On 9/11/18 6:24 PM, Gilmeh Serda wrote:


I think this is no different than RegEx matching, so the routine really
shouldn't be called glob() but the_regex_variations_opus_five().


Maybe your version should be called crippled_glob.

Globbing has a long history, longer than many of the people who use it.

See .


If there really is a need for other stuff with brackets and what not,
this could go into a subclass of glob, say glob.brain_hemorrhage() or
something, for those so inclined to use it. Or maybe a keyword
parameter finicky=True/False.


In their simplest form, the brackets match alternatives.  For example,
file[1234].text matches file1.text, file2.text, file3.text, and
file4.text, but not file_something_else.text.

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


final thoughts on [Re: don't quite understand mailing list]

2018-09-11 Thread Ethan Furman

On 09/07/2018 05:07 PM, Steven D'Aprano wrote:

On Fri, 07 Sep 2018 07:39:33 +0300, Marko Rauhamaa wrote:



I'm with Ethan on this one.

There was nothing in the original posting that merited ridicule.


Then its a good thing there was nothing in the response that was ridicule.


Ridicule may not be the exact word for the contents of the first 
response, but it's close enough.



(A mild rebuke for a mild social faux pas is not ridicule.)


Asking for help is not a social faux pas, at least not on this list.

--
~Ethan~
Python List Moderator

P.S.  Please do not respond to this thread unless you are trying to help 
the original poster.

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


GUI, Python2.7- how to build a loop with a button + textbox

2018-09-11 Thread alon . najman
hi,

on python 2.7 how do I build a loop with a button + textbox?

for example:

I want the user to enter is name and then press "ok" button, I want his name to 
be printed 5 times.


thanks! :) you people are amazing it's almost better then stackoverflow :D
-- 
https://mail.python.org/mailman/listinfo/python-list


Enum with nested classes or with types as members

2018-09-11 Thread Ethan Furman

Greetings!

So the stdlib Enum has been around for a few years now.  Has anyone 
written an enum that either had types as members:


  class Types(Enum):
  Int = int
  Str = str

or that had nested classes:

  class Types(Enum):
 class Contained(Enum):
 circle = 1
 square = 2
 class style:
 something = 'yay!'

?

If you have, why?  Were you able to do everything you wanted, or did you 
have to work around any issues?


I'm asking because in doing some work on Enum it became apparent to me 
that having nested classes was not a smooth, satisfying experience, and 
I'm considering treating them the same way as methods (they will no 
longer be converted into members).


So if you use that functionality, tell me now!  :)

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