Re: Handy utilities = Friday Filosofical Finking

2019-04-01 Thread DL Neil

On 2/04/19 1:56 PM, Cameron Simpson wrote:

On 02Apr2019 13:14, DL Neil  wrote:

On 2/04/19 11:57 AM, Cameron Simpson wrote:

On 29Mar2019 09:32, DL Neil  wrote:
Do you 'keep' these, or perhaps next time you need something you've 
'done before' do you remember when/where a technique was last 
used/burrow into 'history'?

(else, code it from scratch, all over again)


I didn't say it before, but I _loathe_ the "files with code snippets" 
approach. Hard to search, hard to reuse, promotes cut/paste coding which 
means that bugfixes _don't_ make it into all the codebases, just the one 
you're hacking right now.


...and I didn't say it earlier, but *my* unit-of-code in this 
conversation is a function/module and maybe a whole class. However, 
that's me, and directly relates to my background with "subroutine 
libraries" etc.


I'm not sure how much code can still be defined as a "snippet"? This 
idea - how small is too small, plus how large is too... was intended to 
be a part of the conversation...


As far as having unlabelled units of code, describable only as 'a bunch 
of lines which go-together': I agree, the cost of searching probably 
exceeds most peoples' will to live. I guess it is like many other 
decisions: do I spend time now, in the hopes of saving time later...


Yes, the inevitable evolution of this units of code, creates a 
maintenance issue in-and-of itself (another conversational topic I was 
hoping ppl might explore). Personally I don't trust Git sufficiently, 
and have started adding version numbers to the fileNMs so that whereas 
system-X was written to import widgetv1.py, I can update it to 
widgetv2.py as part of system-Y's dev process, and add the possibly/not 
needed update to system-X's backlog.

(well, best laid plans of mice and men...)

However, in my last greenfield project, everything include-d was taken 
as-is and not 'improved'. That might indicate a degree of 'maturity' and 
RoI. Alternatively, that the project was not particularly demanding (it 
was not!)


The other thought I have, in my learning to embrace OOP later in life, 
is that if the 'snippet' is a class, and extensions are needed, perhaps 
a sub-class will side-step such issues, per your warning?

(more best-laid plans, hopes, dreams...)


I put them into modules for import. I've got a tree of Python modules 
named "cs.this", "cs.that" for various things. Then just import stuff 
like any other library module.
Agreed - but Python doesn't (natively) like imports from a 
different/parallel/peer-level dir-tree. (see also Apache httpd)


Well, you have several options:
- modify $PYTHONPATH
- make a virtualenv
- make a symlink; Python imports from the current directory - not my 
  favourite feature, but very handy in the dev environment


Yes, thanks for this. Ideas tossed-around earlier.

As you will have experienced, until recently virtual, Python 
environments had their disadvantages and quirks. I was one of the 
grumblers.


What came along before the recent Py3.? improvements, was VirtualBox. 
This became my preferred virtual modus-operandi, because it very cleanly 
separates one client/department/project from another (and separates 
non-Python components, eg databases and entire file systems). Thus, also 
Python appv2 from v1! If I've managed to convince the client to also run 
their live-system under VBox, then most of the delivery/memory problems 
discussed 'go away'! Sadly nirvana lies just out-there, somewhere beyond 
tomorrow...
(many of these systems sit on a central 'server' somewhere, likely 
sharing a central DB and/or source-data - which is a bit different from 
desktop systems delivered to nn-hundred users; plus web-server projects 
which are similarly 'centralised')



For personal projects (if they aren't just part of that tree) I just 
need to symlink the tree into the local Python library as "cs".

I was doing this.
This works really well for me. In particular, in my development tree I 
symlink to my _dev_ "cs" tree, so that if I modify things (fix a bug, 
add a feature etc) to a cs.* module the change is right there in the 
repo where I can tidy it up and commit it and possibly publish it.


That ability to update the 'repo' as required by the application-dev 
task, is key.



Much of my work is a simple-delivery, ie copying code from my dev m/c 
to the client's PC or server - so I don't 'package it up'* because of 
the (perceived) effort required cf the one-to-one (or maybe a couple) 
machine relationships.
I'm doing something similar right now, but where I've used a cs.* module 
in their code it will go through PyPI as part of the prepare-for-deploy 
process so that they can reproduce the build themselves.


The last step is one I can avoid. In fact, most clients are keen for me 
to do all the computer-technical-stuff, so they can concentrate on their 
research/numbers... ("one-off tasks", discussed earlier)


However, just because it doesn't affect *me* today, still offers a 
learning experience!

Re: How call method from a method in same class?

2019-04-01 Thread Dave

On 4/1/19 10:29 PM, Cameron Simpson wrote:

On 01Apr2019 22:02, Dave  wrote:
As classes get more complex, it is good to call a function to do some 
of the processing, and make the code easier to follow.  My question is 
how to do that?  I've attached some silly code to illustrate the 
point.  The error is: name 'validScale' is not defined.  Well, yes it 
is, but maybe not the correct way.  Suggestions?


It is and it isn't. See below:


class TempConverter():
   """ Temperature Converter converts a tempeature from one scale
   to another scale.  For example: 32, F, C will return
   0 degrees C
   """

[...]

   def validScale(self, scaleName):
   if scaleName.upper == 'F' or 'C' or 'K':
   return True
   else:
   return False

   def convertTemp(self):
   """ Converts temperature scale if scales valid."""
   if validScale(self.scale):
   scaleValid = True

[...]

It is an instance method, so:

    if self.validScale(self.scale)

would resolve the name. However, there are several things worth 
discussing here.


First up, validScale itself returns a Boolean, so just return the test 
result. Change:


    if scaleName.upper == 'F' or 'C' or 'K':
    return True
    else:
    return False

into:

    return scaleName.upper == 'F' or 'C' or 'K'

Second, the condition is buggy. You want this:

    return scaleName.upper() in ('F', 'C', 'K')

i.e. you need to call (the "()") the .upper method, and you need to 
check if the result is in your collection of valid results.


This expression:

    value == A or B or C

means: True if value == A, otherwise B if B is true, otherwise C.

The next thing to observe is that you're testing whether self.scale is 
valid. Normal practice would be to make that test in __init__, and raise 
a ValueError if it is not so:


    def __init__(self, .scale...):
  if scale.upper() not in ('F', 'C', 'K'):
    raise ValueError("invalid scale %r: expected one of F, C or K" % 
(scale,))
why recite the scale in the message? Because it makes the offending 
value obvious. In particular, if for example you called this incorrectly 
and had the temperature in there instead of the scale that will be 
trivial to debug from the message.


Of course, you actually want to be able to test any scal evalue for 
validity, not just the one stuffed into your instance (.scale). So lets 
revisit the validScale method:


    def validScale(self, scale):
  return scaleName.upper() in ('F', 'C', 'K')

You'll notice that it doesn't depend in "self". Or, for that matter, the 
class. So this is a "static" method: a function defined in the class for 
conceptual clarity, but not with any dependence on the class itself or a 
particular class instance. So:


    @staticmethod
    def validScale(scale):
  return scaleName.upper() in ('F', 'C', 'K')

In __init__, and elsewhere, you can still call this from the instance:

    def __init__(self, .scale...):
  if not self.validScale(scale):
    raise ValueError("invalid scale %r: expected one of F, C or K" % 
(scale,))
You can also call this from _outside_ the class, for example for other 
validation:


    scale = input("Enter a temperate scale name (F, C or K): ")
    if not TempConverter.validScale(scale):
  print("Bad! Bad user!")


   newScaleValid = True


Again, validScale returns a Boolean. So you could have just gone:

    newScaleValid = self.validScale(newScale)


   if scaleValid and newScaleValid:
   print('Scale converted')
   else:
   msg = "There was and error with the scales entered.\n"
   msg = msg + "You entered: " + self.scale
   msg = msg + ' ' 'and' + self.newScale
   print(msg)

if __name__ == "__main__":
   myclass = TempConverter(32, 'f', 'c')
   myclass.convertTemp()


My personal inclination would be do define a Temperature class with a 
convert function to be used like this:


    temp = Temperature(32, 'f')
    tempC = temp.convert('c')

This reduces the complexity of the class and IMO makes it easier to use 
elsewhere.



BTW, you get an instance back from tempConverter(...), not a class. So 
don't call it "myclass".


Cheers,
Cameron Simpson 


Cameron,

I'm going to need a while to work through this.  As I mentioned, this 
was quick and dirty code just to illustrate a point - not intended to be 
good code.  So I'll take a close read tomorrow.  Thanks again!!


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


Re: Handy utilities = Friday Filosofical Finking

2019-04-01 Thread Chris Angelico
On Tue, Apr 2, 2019 at 1:21 PM DL Neil  wrote:
> > Sometimes, I recollect and reference, which creates some very weird
> > interdependencies until I get around to refactoring...
>
> but some fairly hairy "technical debt" meantime?
>
>
> > https://github.com/Rosuav/MegaClip/blob/master/deviquotes.py
> > imports https://github.com/Rosuav/shed/blob/master/emotify.py
> > which gets an API key from the non-sample version of
> > https://github.com/Rosuav/MustardMine/blob/master/config_sample.py
> > and the end result of deviquotes is to rebuild this
> > https://github.com/DeviCatOutlet/devicatoutlet.github.io/blob/master/quotes.md
>
> The twists and turns are positively admirable, but promoting the above
> as a training exemplar might not be the best idea!

Oh, I *never* said this was best practise! Let me be clear here: This
is NOT an organizational structure. It is a lack-of-organization
structure.

> Back to the original question(s): something I didn't want to do was to
> have a hard-coding of the import sourceDIR (per above). Whilst the
> PYTHONPATH is (at the very least) a form of "hard coding", at least I
> can do that to/on a client's m/c separately/in-addition to loading the
> s/w AND know that the Python code 'there' is the same as I have (in
> repo) 'here'!

This actually isn't so bad though. The paths are deliberately
relative, and the only requirement is: If you want these projects to
interoperate, clone them into the same parent directory. So you can
have a "projects" directory, or drop them all into your home
directory, or stick 'em into a "stuff that's trying to work together"
directory, or anything like that, just as long as they're peers off
the same parent.

> > So running that one script can potentially involve four different
> > repositories, because I haven't yet made any of the pieces into proper
> > libraries...
>
> - and if I did the same, would you pay me (as much) for delivering such?
> (different rules for personal stuff)

This is personal, so the "different rules" are the ones that apply.

For commercial software that's expected to be able to run on arbitrary
people's machines, tidying this sort of thing up would be a
pre-deployment priority. But then the question would be: which part of
this is being sold? Mustard Mine stands alone (the others call on it),
so it can viably be distributed - and in fact, is designed to be. None
of the others really need to be, so it's hard to answer in theory.

But you're absolutely right that this is the sort of thing that makes
it hard to sell a piece of software. Gotta have clean distribution.

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


Re: How call method from a method in same class?

2019-04-01 Thread Cameron Simpson

On 01Apr2019 22:02, Dave  wrote:
As classes get more complex, it is good to call a function to do some 
of the processing, and make the code easier to follow.  My question is 
how to do that?  I've attached some silly code to illustrate the 
point.  The error is: name 'validScale' is not defined.  Well, yes it 
is, but maybe not the correct way.  Suggestions?


It is and it isn't. See below:


class TempConverter():
   """ Temperature Converter converts a tempeature from one scale
   to another scale.  For example: 32, F, C will return
   0 degrees C
   """

[...]

   def validScale(self, scaleName):
   if scaleName.upper == 'F' or 'C' or 'K':
   return True
   else:
   return False

   def convertTemp(self):
   """ Converts temperature scale if scales valid."""
   if validScale(self.scale):
   scaleValid = True

[...]

It is an instance method, so:

   if self.validScale(self.scale)

would resolve the name. However, there are several things worth 
discussing here.


First up, validScale itself returns a Boolean, so just return the test 
result. Change:


   if scaleName.upper == 'F' or 'C' or 'K':
   return True
   else:
   return False

into:

   return scaleName.upper == 'F' or 'C' or 'K'

Second, the condition is buggy. You want this:

   return scaleName.upper() in ('F', 'C', 'K')

i.e. you need to call (the "()") the .upper method, and you need to 
check if the result is in your collection of valid results.


This expression:

   value == A or B or C

means: True if value == A, otherwise B if B is true, otherwise C.

The next thing to observe is that you're testing whether self.scale is 
valid. Normal practice would be to make that test in __init__, and raise 
a ValueError if it is not so:


   def __init__(self, .scale...):
 if scale.upper() not in ('F', 'C', 'K'):
   raise ValueError("invalid scale %r: expected one of F, C or K" % (scale,)) 

why recite the scale in the message? Because it makes the offending 
value obvious. In particular, if for example you called this incorrectly 
and had the temperature in there instead of the scale that will be 
trivial to debug from the message.


Of course, you actually want to be able to test any scal evalue for 
validity, not just the one stuffed into your instance (.scale). So lets 
revisit the validScale method:


   def validScale(self, scale):
 return scaleName.upper() in ('F', 'C', 'K')

You'll notice that it doesn't depend in "self". Or, for that matter, the 
class. So this is a "static" method: a function defined in the class for 
conceptual clarity, but not with any dependence on the class itself or a 
particular class instance. So:


   @staticmethod
   def validScale(scale):
 return scaleName.upper() in ('F', 'C', 'K')

In __init__, and elsewhere, you can still call this from the instance:

   def __init__(self, .scale...):
 if not self.validScale(scale):
   raise ValueError("invalid scale %r: expected one of F, C or K" % (scale,)) 

You can also call this from _outside_ the class, for example for other 
validation:


   scale = input("Enter a temperate scale name (F, C or K): ")
   if not TempConverter.validScale(scale):
 print("Bad! Bad user!")


   newScaleValid = True


Again, validScale returns a Boolean. So you could have just gone:

   newScaleValid = self.validScale(newScale)


   if scaleValid and newScaleValid:
   print('Scale converted')
   else:
   msg = "There was and error with the scales entered.\n"
   msg = msg + "You entered: " + self.scale
   msg = msg + ' ' 'and' + self.newScale
   print(msg)

if __name__ == "__main__":
   myclass = TempConverter(32, 'f', 'c')
   myclass.convertTemp()


My personal inclination would be do define a Temperature class with a 
convert function to be used like this:


   temp = Temperature(32, 'f')
   tempC = temp.convert('c')

This reduces the complexity of the class and IMO makes it easier to use 
elsewhere.



BTW, you get an instance back from tempConverter(...), not a class. So 
don't call it "myclass".


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


Re: How call method from a method in same class?

2019-04-01 Thread Dave

On 4/1/19 10:02 PM, Dave wrote:
As classes get more complex, it is good to call a function to do some of 
the processing, and make the code easier to follow.  My question is how 
to do that?  I've attached some silly code to illustrate the point.  The 
error is: name 'validScale' is not defined.  Well, yes it is, but maybe 
not the correct way.  Suggestions?


Dave,

class TempConverter():
     """ Temperature Converter converts a tempeature from one scale
     to another scale.  For example: 32, F, C will return
     0 degrees C
     """

     def __init__(self, temperature, scale, newScale):
     self.temperature = temperature
     self.scale = scale
     self.newScale = newScale

     def validScale(self, scaleName):
     if scaleName.upper == 'F' or 'C' or 'K':
     return True
     else:
     return False

     def convertTemp(self):
     """ Converts temperature scale if scales valid."""
     if validScale(self.scale):
     scaleValid = True
     if validScale(self.newScale):
     newScaleValid = True
     if scaleValid and newScaleValid:
     print('Scale converted')
     else:
     msg = "There was and error with the scales entered.\n"
     msg = msg + "You entered: " + self.scale
     msg = msg + ' ' 'and' + self.newScale
     print(msg)

if __name__ == "__main__":
     myclass = TempConverter(32, 'f', 'c')
     myclass.convertTemp()


Thanks all for your (ready, wait for it) self-lessness help (get it?)

Dave (laughing)

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


Re: How call method from a method in same class?

2019-04-01 Thread Dave

On 4/1/19 10:12 PM, Irv Kalb wrote:



On Apr 1, 2019, at 7:02 PM, Dave  wrote:

As classes get more complex, it is good to call a function to do some of the 
processing, and make the code easier to follow.  My question is how to do that? 
 I've attached some silly code to illustrate the point.  The error is: name 
'validScale' is not defined.  Well, yes it is, but maybe not the correct way.  
Suggestions?

Dave,

class TempConverter():
""" Temperature Converter converts a tempeature from one scale
to another scale.  For example: 32, F, C will return
0 degrees C
"""

def __init__(self, temperature, scale, newScale):
self.temperature = temperature
self.scale = scale
self.newScale = newScale

def validScale(self, scaleName):
if scaleName.upper == 'F' or 'C' or 'K':
return True
else:
return False

def convertTemp(self):
""" Converts temperature scale if scales valid."""
if validScale(self.scale):
scaleValid = True
if validScale(self.newScale):
newScaleValid = True
if scaleValid and newScaleValid:
print('Scale converted')
else:
msg = "There was and error with the scales entered.\n"
msg = msg + "You entered: " + self.scale
msg = msg + ' ' 'and' + self.newScale
print(msg)

if __name__ == "__main__":
myclass = TempConverter(32, 'f', 'c')
myclass.convertTemp()
--
https://mail.python.org/mailman/listinfo/python-list



To answer your specific question, you call a method in the same class by 
calling:  self.methodName   For example:  self.validScale

However, once you fix that, you wind find that the if statement in that method 
is not built correctly.

Also, since the variable self.scale is already set in your __init__ method, 
there is no need to pass it into your function.  You could just use self.scale 
inside that method.

Irv



Irv,

Thanks for the response!  I realize the code is junk - just done to 
illustrate the problem.


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


Re: Handy utilities = Friday Filosofical Finking

2019-04-01 Thread DL Neil

On 2/04/19 1:25 PM, Chris Angelico wrote:

On Tue, Apr 2, 2019 at 11:16 AM DL Neil  wrote:

One of the points which intrigue me is that my colleagues don't keep
snippets/a library, preferring to remember (hah!) when/where they used
particular techniques in the past, and copying/duplicating, to fit the
new system's requirements. Am wondering if this is true beyond our
little band?

Until I've done something the same way two or three times, I just
recollect and steal. There are a few things that are in the back of my
mind to refactor out and make into libraries, but it's hard when they
aren't actually identical. Otherwise, it waits till there are a few
replicas, and then might get put into a central location somewhere.


In the ?good, old days (when computers were lubricated with open-fire 
rendered dinosaur fat) I would have followed such a practice!


However... when I was converted to the 'religion' of OOP, JIT/Agile, 
etc; I started working on one function/method (and class) at a time. 
(which inherently involves a balancing act between preparing some 
'useful tools' and YAGNI) Accordingly, extracting 'useful bits' into a, 
or to form a new, module is not difficult - and only requires the 
addition of an import statement to the original pgm/module. Accordingly, 
I try (very hard) not to find myself with the 'thrills' which you 
describe here...

(but hey, I'm an old ...)

Such also makes it easier to take care of the 'almost identical' nature 
of the programmer's existence...


Having said that, and cast aspersions about other members of the team 
'here', I couldn't believe that I'm the only ... Python coder in this world?




Sometimes, I recollect and reference, which creates some very weird
interdependencies until I get around to refactoring...


but some fairly hairy "technical debt" meantime?



https://github.com/Rosuav/MegaClip/blob/master/deviquotes.py
imports https://github.com/Rosuav/shed/blob/master/emotify.py
which gets an API key from the non-sample version of
https://github.com/Rosuav/MustardMine/blob/master/config_sample.py
and the end result of deviquotes is to rebuild this
https://github.com/DeviCatOutlet/devicatoutlet.github.io/blob/master/quotes.md


The twists and turns are positively admirable, but promoting the above 
as a training exemplar might not be the best idea!


Back to the original question(s): something I didn't want to do was to 
have a hard-coding of the import sourceDIR (per above). Whilst the 
PYTHONPATH is (at the very least) a form of "hard coding", at least I 
can do that to/on a client's m/c separately/in-addition to loading the 
s/w AND know that the Python code 'there' is the same as I have (in 
repo) 'here'!





So running that one script can potentially involve four different
repositories, because I haven't yet made any of the pieces into proper
libraries...


- and if I did the same, would you pay me (as much) for delivering such? 
(different rules for personal stuff)


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


Re: How call method from a method in same class?

2019-04-01 Thread Dan Sommers

On 4/1/19 10:02 PM, Dave wrote:


  def validScale(self, scaleName):
  if scaleName.upper == 'F' or 'C' or 'K':
  return True
  else:
  return False

  def convertTemp(self):
  """ Converts temperature scale if scales valid."""
  if validScale(self.scale):
  scaleValid = True
  if validScale(self.newScale):
  newScaleValid = True
  if scaleValid and newScaleValid:
  print('Scale converted')
  else:
  msg = "There was and error with the scales entered.\n"
  msg = msg + "You entered: " + self.scale
  msg = msg + ' ' 'and' + self.newScale
  print(msg)


Note that validscale has a self parameter.  Call it just
like you would from outside the class:

if self.validScale(self.newScale):
newScaleValid = True

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


Re: How call method from a method in same class?

2019-04-01 Thread Irv Kalb


> On Apr 1, 2019, at 7:02 PM, Dave  wrote:
> 
> As classes get more complex, it is good to call a function to do some of the 
> processing, and make the code easier to follow.  My question is how to do 
> that?  I've attached some silly code to illustrate the point.  The error is: 
> name 'validScale' is not defined.  Well, yes it is, but maybe not the correct 
> way.  Suggestions?
> 
> Dave,
> 
> class TempConverter():
>""" Temperature Converter converts a tempeature from one scale
>to another scale.  For example: 32, F, C will return
>0 degrees C
>"""
> 
>def __init__(self, temperature, scale, newScale):
>self.temperature = temperature
>self.scale = scale
>self.newScale = newScale
> 
>def validScale(self, scaleName):
>if scaleName.upper == 'F' or 'C' or 'K':
>return True
>else:
>return False
> 
>def convertTemp(self):
>""" Converts temperature scale if scales valid."""
>if validScale(self.scale):
>scaleValid = True
>if validScale(self.newScale):
>newScaleValid = True
>if scaleValid and newScaleValid:
>print('Scale converted')
>else:
>msg = "There was and error with the scales entered.\n"
>msg = msg + "You entered: " + self.scale
>msg = msg + ' ' 'and' + self.newScale
>print(msg)
> 
> if __name__ == "__main__":
>myclass = TempConverter(32, 'f', 'c')
>myclass.convertTemp()
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 

To answer your specific question, you call a method in the same class by 
calling:  self.methodName   For example:  self.validScale

However, once you fix that, you wind find that the if statement in that method 
is not built correctly.

Also, since the variable self.scale is already set in your __init__ method, 
there is no need to pass it into your function.  You could just use self.scale 
inside that method.

Irv

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


How call method from a method in same class?

2019-04-01 Thread Dave
As classes get more complex, it is good to call a function to do some of 
the processing, and make the code easier to follow.  My question is how 
to do that?  I've attached some silly code to illustrate the point.  The 
error is: name 'validScale' is not defined.  Well, yes it is, but maybe 
not the correct way.  Suggestions?


Dave,

class TempConverter():
""" Temperature Converter converts a tempeature from one scale
to another scale.  For example: 32, F, C will return
0 degrees C
"""

def __init__(self, temperature, scale, newScale):
self.temperature = temperature
self.scale = scale
self.newScale = newScale

def validScale(self, scaleName):
if scaleName.upper == 'F' or 'C' or 'K':
return True
else:
return False

def convertTemp(self):
""" Converts temperature scale if scales valid."""
if validScale(self.scale):
scaleValid = True
if validScale(self.newScale):
newScaleValid = True
if scaleValid and newScaleValid:
print('Scale converted')
else:
msg = "There was and error with the scales entered.\n"
msg = msg + "You entered: " + self.scale
msg = msg + ' ' 'and' + self.newScale
print(msg)

if __name__ == "__main__":
myclass = TempConverter(32, 'f', 'c')
myclass.convertTemp()
--
https://mail.python.org/mailman/listinfo/python-list


Re: Handy utilities = Friday Filosofical Finking

2019-04-01 Thread Cameron Simpson

On 02Apr2019 13:14, DL Neil  wrote:

On 2/04/19 11:57 AM, Cameron Simpson wrote:

On 29Mar2019 09:32, DL Neil  wrote:
Do you 'keep' these, or perhaps next time you need something you've 
'done before' do you remember when/where a technique was last 
used/burrow into 'history'?

(else, code it from scratch, all over again)


I didn't say it before, but I _loathe_ the "files with code snippets" 
approach. Hard to search, hard to reuse, promotes cut/paste coding which 
means that bugfixes _don't_ make it into all the codebases, just the one 
you're hacking right now.


I put them into modules for import. I've got a tree of Python 
modules named "cs.this", "cs.that" for various things. Then just 
import stuff like any other library module.


Agreed - but Python doesn't (natively) like imports from a 
different/parallel/peer-level dir-tree. (see also Apache httpd)


Well, you have several options:

- modify $PYTHONPATH

- make a virtualenv

- make a symlink; Python imports from the current directory - not my 
 favourite feature, but very handy in the dev environment


For personal projects (if they aren't just part of that tree) I just 
need to symlink the tree into the local Python library as "cs".


I was doing this.


This works really well for me. In particular, in my development tree I 
symlink to my _dev_ "cs" tree, so that if I modify things (fix a bug, 
add a feature etc) to a cs.* module the change is right there in the 
repo where I can tidy it up and commit it and possibly publish it.


Much of my work is a simple-delivery, ie copying code from my dev m/c 
to the client's PC or server - so I don't 'package it up'* because of 
the (perceived) effort required cf the one-to-one (or maybe a couple) 
machine relationships.


I'm doing something similar right now, but where I've used a cs.* module 
in their code it will go through PyPI as part of the prepare-for-deploy 
process so that they can reproduce the build themselves.


In my case the deploy.sh script makes a directory tree with a copy of 
the released code (from a repo tag name - "hg archive" for me, there's 
an equivalent git command).  That tree contains a prep.sh script which 
runs on the target machine to build the virtualenv and likewise the 
javascript side which is used for the web front end.


So deploy for me is:

- get the code ready (committed, tagged) at some suitable good phase

- run "./deploy.sh release-tag" which makes a deployable tree

- rsync onto the target (into a shiny new tree - I'll twiddle a symlink 
 when it goes "live")


- run "./prep.sh" in the target, which fetches components etc

The advantage of the prep.sh step is that (a) the target matches the 
target host (where that matters, for example the local virtualenv will 
run off the target host Python and so forth), and _also_ (b) it serves 
as doco for me on how to build the app: if prep.sh doesn't work, my 
client doesn't have a working recipe for building their app.


I still need to add some prechecks to the deploy, like "is the venv 
requirements file commented to the repo" etc.


However, during 'delivery' to another machine, have to remember to 
rsync/copy including the symlink, as well as to transfer both 
dir-trees.


By making a local virtualenv and getting my modules through PyPI (pip 
install) this issue is bypassed: there's the client code library 
(rsynced) and the third party modules fetched via PyPI. (Not just my 
cs.* modules if any, but also all the other modules required.)


Recently, stopped to organise the code into (more) modules (as also 
suggested here) and moved to adding the 'utilities' directories into 
PYTHONPATH. Now I have to remember to modify that on the/each target 
m/c!


Script it. Include the script in the rsync.

If I get something well enough defined and sufficiently cleaned up for 
use beyond my own code (or just good enough that others might want 
it), up it goes to PyPI so that it can just be "pip install"ed.


So I've got this huge suite of modules with stuff in them, and a 
subset of those modules are published to PyPI for third party reuse.


Am dubious that any of the 'little bits' that I have collected are 
sufficiently worthy, but that's 'proper' F/LOSSy thinking!


If you're reusing your little bits then they need organisation into 
modules so that you can include them with the main code without treading 
on others' namespaces.


Publishing to PyPI is a very very optional step; the critical thing is 
breaking stuff up into modules; rsyncing them is then easy and you have 
a common codebase which _were formerly_ snippets for reuse.


Also, putting them in modules and using them that way forces you to make 
you snippets reusable instead of cut/patse/adaptable. Win win.


*will be interested to hear if you think I should stop 'being lazy' and 
invest some time-and-effort into learning 'packaging' options and do 
things 'properly'?professionally...


There's real pain there. The first time I did this (2015?) I basicly 
spent

Re: Handy utilities = Friday Filosofical Finking

2019-04-01 Thread Chris Angelico
On Tue, Apr 2, 2019 at 11:16 AM DL Neil  wrote:
> One of the points which intrigue me is that my colleagues don't keep
> snippets/a library, preferring to remember (hah!) when/where they used
> particular techniques in the past, and copying/duplicating, to fit the
> new system's requirements. Am wondering if this is true beyond our
> little band?
>

Until I've done something the same way two or three times, I just
recollect and steal. There are a few things that are in the back of my
mind to refactor out and make into libraries, but it's hard when they
aren't actually identical. Otherwise, it waits till there are a few
replicas, and then might get put into a central location somewhere.

Sometimes, I recollect and reference, which creates some very weird
interdependencies until I get around to refactoring...

https://github.com/Rosuav/MegaClip/blob/master/deviquotes.py
imports https://github.com/Rosuav/shed/blob/master/emotify.py
which gets an API key from the non-sample version of
https://github.com/Rosuav/MustardMine/blob/master/config_sample.py
and the end result of deviquotes is to rebuild this
https://github.com/DeviCatOutlet/devicatoutlet.github.io/blob/master/quotes.md

So running that one script can potentially involve four different
repositories, because I haven't yet made any of the pieces into proper
libraries...

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


Re: Handy utilities = Friday Filosofical Finking

2019-04-01 Thread DL Neil

Gidday Cameron,

Thanks for this - some thoughts below:-


On 2/04/19 11:57 AM, Cameron Simpson wrote:

On 29Mar2019 09:32, DL Neil  wrote:
How do you keep, use, and maintain those handy snippets, functions, 
classes... - units of code, which you employ over-and-over again?

Having coded 'stuff' once, most of us will keep units of code,
"utilities", which we expect will be useful in-future (DRY principle), 
eg functions to rename files, choose unique back-up/new fileNMs, 
accessing a DB, journalling (logging) start/stop msgs, building specs 
from YAML/JSON/XML/.ini config files (tongue~cheek), etc.


Do you 'keep' these, or perhaps next time you need something you've 
'done before' do you remember when/where a technique was last 
used/burrow into 'history'?

(else, code it from scratch, all over again)


I put them into modules for import. I've got a tree of Python modules 
named "cs.this", "cs.that" for various things. Then just import stuff 
like any other library module.


Agreed - but Python doesn't (natively) like imports from a 
different/parallel/peer-level dir-tree. (see also Apache httpd)



For personal projects (if they aren't just part of that tree) I just 
need to symlink the tree into the local Python library as "cs".


I was doing this.

Much of my work is a simple-delivery, ie copying code from my dev m/c to 
the client's PC or server - so I don't 'package it up'* because of the 
(perceived) effort required cf the one-to-one (or maybe a couple) 
machine relationships.


However, during 'delivery' to another machine, have to remember to 
rsync/copy including the symlink, as well as to transfer both dir-trees.



Recently, stopped to organise the code into (more) modules (as also 
suggested here) and moved to adding the 'utilities' directories into 
PYTHONPATH. Now I have to remember to modify that on the/each target m/c!



(and you can guess what happens when I'm asked to remember something! 
Although, in my defence, I know this and (apparently) 
write-down/document a lot more than many/most of my colleagues. (puff, 
puff) )



If I get something well enough defined and sufficiently cleaned up for 
use beyond my own code (or just good enough that others might want it), 
up it goes to PyPI so that it can just be "pip install"ed.


So I've got this huge suite of modules with stuff in them, and a subset 
of those modules are published to PyPI for third party reuse.


Am dubious that any of the 'little bits' that I have collected are 
sufficiently worthy, but that's 'proper' F/LOSSy thinking!


*will be interested to hear if you think I should stop 'being lazy' and 
invest some time-and-effort into learning 'packaging' options and do 
things 'properly'?professionally...




Happy to elaborate on the details.


One of the points which intrigue me is that my colleagues don't keep 
snippets/a library, preferring to remember (hah!) when/where they used 
particular techniques in the past, and copying/duplicating, to fit the 
new system's requirements. Am wondering if this is true beyond our 
little band?


Yet, here on the list, interest was shown in 'being organised' (even if 
few have actually weighed-in)...



Thanks!
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: python os.chdir() Windows Error 2

2019-04-01 Thread eryk sun
On 4/1/19, grossmu...@gmail.com  wrote:
>
> os.chdir('C:\\Users\\Ayla\\Documents\\Uni\\Master_Umweltingenieurwesen\\
> Study_Project\\kerschbaum_input')
> os.chdir('C:/Users/Ayla/Documents/Uni/Master_Umweltingenieurwesen/
> Study_Project/kerschbaum_input')

These string literals should work if the path exists. You're getting
ERROR_FILE_NOT_FOUND (2), which means that "kerschbaum_input" doesn't
exist. Any other missing directory component would result in
ERROR_PATH_NOT_FOUND (3).

> os.chdir('C:\Users\Ayla\Documents\Uni\Master_Umweltingenieurwesen\
> Study_Project\kerschbaum_input')
> os.chdir('C:\\Users\Ayla\Documents\Uni\Master_Umweltingenieurwesen\
> Study_Project\kerschbaum_input')

"\U" is a Unicode escape sequence in Python 3 (e.g. "\U263A" for
"☺") , so "\Us" or "\Un" is a syntax error. In Python 2, this is only
the case for a [u]nicode string literal (e.g. u"C:\Users" is an
error), but we should be using use Unicode for Windows paths even in
Python 2 (at least as much as it permits).

> os.chdir('C://Users/Ayla/Documents/Uni/Master_Umweltingenieurwesen/
> Study_Project/kerschbaum_input')
> os.chdir('C://Users//Ayla//Documents//Uni/vMaster_Umweltingenieurwesen//
> Study_Project//kerschbaum_input')

Sequential slashes are allowed in general. The system collapses them
to a single slash. Except more than 2 slashes at the beginning of a
UNC path is always collapsed to 3 slashes, which is an error. That
said, doubling forward slashes in a string literal isn't good form.
It's not escaping anything. It's just two slashes.

> and \\?\c instead of C.

The \\?\ prefix bypasses normalization. For regular Windows
filesystems, this style of path must contain only backslash as the
path separator (no forward slashes) and must be Unicode and fully
qualified. In this case, the final component can use a reserved DOS
device name (e.g. "nul.txt") or end in trailing spaces and/or dots
(e.g. "spam. . ."). That said, using such reserved names is not
recommended when creating new files.

Usually the \\?\ prefix is used to bypass the classic DOS path length
limits (e.g. 247, 258, or 259 characters depending on the context).
However, this is not the case for os.chdir (i.e. WINAPI
SetCurrentDirectoryW). The working directory is hard limited to 258
characters. In Windows 10 it can exceed this limit if long-path
support is enabled in the registry and application (Python 3.6+), but
I don't recommend it because subprocess.Popen (i.e. WINAPI
CreateProcessW) will fail if the inherited working directory exceeds
the 258 character limit.

> I also added the path (in advanced system settings) of the folder.

The PATH environment variable contains directories that are searched
by WINAPI SearchPathW, CreateProcessW, and LoadLibraryExW (by
default). Are you trying to import an extension module that has
dependent DLLs?

FYI, for future reference, it's planned (and already committed) for
Python 3.8 to no longer search the working directory or PATH when
loading dependent DLLs of extension modules. As before, it will look
for DLL dependencies in the directory of the extension module, the
application directory (i.e. location of python.exe), and the System32
directory. But now instead of searching PATH it will use the loader's
secure search path. We'll be able to extend this search path with the
new function os.add_dll_directory, which wraps WINAPI AddDllDirectory.
A similar change is slated for ctypes.CDLL (and derived classes such
as WinDLL), except including the directory of the target DLL in the
search will require using a qualified path, e.g.
ctypes.CDLL('./spam.dll') or ctypes.CDLL('C:/eggs/spam.dll').
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handy utilities = Friday Filosofical Finking

2019-04-01 Thread Cameron Simpson

On 29Mar2019 09:32, DL Neil  wrote:
How do you keep, use, and maintain those handy snippets, functions, 
classes... - units of code, which you employ over-and-over again?
Having coded 'stuff' once, most of us will keep units of code, 

"utilities", which we expect will be useful in-future (DRY principle), 
eg functions to rename files, choose unique back-up/new fileNMs, 
accessing a DB, journalling (logging) start/stop msgs, building specs 
from YAML/JSON/XML/.ini config files (tongue~cheek), etc.


Do you 'keep' these, or perhaps next time you need something you've 
'done before' do you remember when/where a technique was last 
used/burrow into 'history'?

(else, code it from scratch, all over again)


I put them into modules for import. I've got a tree of Python modules 
named "cs.this", "cs.that" for various things. Then just import stuff 
like any other library module.


For personal projects (if they aren't just part of that tree) I just 
need to symlink the tree into the local Python library as "cs".


If I get something well enough defined and sufficiently cleaned up for 
use beyond my own code (or just good enough that others might want it), 
up it goes to PyPI so that it can just be "pip install"ed.


So I've got this huge suite of modules with stuff in them, and a subset 
of those modules are published to PyPI for third party reuse.


Happy to elaborate on the details.

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


Re: Syntax for one-line "nonymous" functions in "declaration style"

2019-04-01 Thread Alexey Muranov

On lun., avril 1, 2019 at 6:00 PM, python-list-requ...@python.org wrote:
On Sun, Mar 31, 2019 at 1:09 PM Alexey Muranov 


wrote:


 On dim., Mar 31, 2019 at 6:00 PM, python-list-requ...@python.org 
wrote:

 > On Sat, Mar 30, 2019, 5:32 AM Alexey Muranov
 > 
 > wrote:
 >
 >>
 >>  On ven., Mar 29, 2019 at 4:51 PM, python-list-requ...@python.org
 >> wrote:
 >>  >
 >>  > There could perhaps be a special case for lambda expressions 
such

 >>  >  that,
 >>  > when they are directly assigned to a variable, Python would 
use

 >> the
 >>  > variable name as the function name. I expect this could be
 >>  >  accomplished by
 >>  > a straightforward transformation of the AST, perhaps even by 
just

 >>  >  replacing
 >>  > the assignment with a def statement.
 >>
 >>  If this will happen, that is, if in Python assigning a
 >> lambda-defined
 >>  function to a variable will mutate the function's attributes, or
 >> else,
 >>  if is some "random" syntactically-determined cases
 >>
 >>  f = ...
 >>
 >>  will stop being the same as evaluating the right-hand side and
 >>  assigning the result to "f" variable, it will be a fairly good 
extra

 >>  reason for me to go away from Python.
 >>
 >
 > Is there a particular reason you don't like this? It's not too
 > different
 > from the syntactic magic Python already employs to support the
 > 0-argument
 > form of super().

 I do not want any magic in a programming language i use, especially 
if

 it breaks simple rules.

 I do not like 0-argument `super()` either, but at least I do not 
have

 to use it.


Well, you wouldn't have to use my suggestion either, since it only 
applies

to assignments of the form "f = lambda x: blah". As has already been
stated, the preferred way to do this is with a def statement. So just 
use a
def statement for this, and it wouldn't affect you (unless you 
*really*

want the function's name to be "" for some reason).


I only see a superficial analogy with `super()`, but perhaps it is 
because you did not give much details of you suggestion.


Not only i do not have to use `super()` (i do not have to use Python 
either), but the magic behaviour of `super` is explained by special 
implicit environments in which some blocks of code are executed.  
Though this looks somewhat hackish, it gives me no clue of how your 
idea of mutating objects during assignment is supposed to work.


On the other hand, i do use assignment in Python, and you seem to 
propose to get rid of assignment or to break it.


Note that

   foo.bar = baz

and

   foo[bar] = baz

are not assignments but method calls, but

   foo = bar

it an assignment (if i understand the current model correctly).

Do you propose to desugar it into a method/function call and to get rid 
of assignments in the language completely? Will the user be able to 
override this method? Something like:


   setvar("foo", bar)  # desugaring of foo = bar

Would the assignment operation remain in the language under a different 
name?  Maybe,


   foo <- bar

?

I am so perplexed by the proposed behaviour of `f = lambda...`, that i 
need to ask the followng: am i right to expact that


 1.

 f = lambda x: x,
 g = lambda x: x*x

 2.

 (f, g) = (lambda x: x, lambda x: x*x)

 3.

 (f, g) = _ = (lambda x: x, lambda x: x*x)

 4.

 f = (lambda x: x)(lambda x: x)
 g = (lambda x: x)(lambda x: x*x)

Will all have the same net effect?

I suppose in any case that

   return lambda x: 

and

   result = lambda x: 
   return result

would not return the same result, which is not what i want.

I tried to imagine what semantics of the language could cause your 
proposed behaviour of `f = lambda...` and couldn't think of anything 
short of breaking the language.



That said, that's also the reason why this probably wouldn't happen. 
Why go

to the trouble of fixing people's lambda assignments for them when the
preferred fix would be for them to do it themselves by replacing them 
with

def statements?


It is not fixing, it is breaking.

Alexey.


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


Logging module and datetime - oil & water for some reason?

2019-04-01 Thread Skip Montanaro
I assiduously avoided using Python's logging package for about the
first dozen years of its existence. I eventually gave in and started
using it relatively recently in the guise of a thin wrapper provided
by a colleague at work. Today I had occasion to tweak the timestamp
format only to discover that logging still uses time.localtime or
time.gmtime as its underlying source of time fields, so subsecond
timestamps are hacked in, with no straightforward way to log both
milliseconds and the timezone in normal order. I have need for both,
as I work for a company with offices in multiple timezones, and
sometimes need subsecond time resolution for quick-n-dirty analysis.

I stole a custom formatter class from a StackOverflow thread and am
now back in business (milliseconds *and* timezones, yay!). Still,
peeking at the 2.7 documentation, I see that both the logging package
and the datetime module were added to the standard library in Python
2.3 (2003). Why is logging still relying on the suboptimal
time.{localtime,gmtime} API? Surely, if there was no
backwards-compatible way to introduce datetime into the system, a
small breaking change could have been made for Python 3000 and
probably affected very few users.

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


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, Abdur-Rahmaan Janhangeer  wrote:
> Since this is IRC, you might want to see a demo here:
> https://github.com/Abdur-rahmaanJ/honeybot/blob/master/honeybot/main.py


Yes. However get these def text() and loop while 1: working together.

def text():
while True:
mess = input("> ")
print(mess)
s.send(bytes("PRIVMSG " + " "+ channel + " " + ":" + mess  + "\n", 
"UTF-8"))

text()

while 1:
data = s.recv(4096).decode('utf-8')
print(data)
if data.find('PING') != -1:
s.send(str('PONG ' + data.split(':')[1] + '\r\n').encode())
print('PONG sent \n')



s.close()

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


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, Rhodri James  wrote:
>
> I'm not an expert, but looking at RFC-1459 it looks like your final 
> parameter (the message) needs to be preceded by a colon.  In other words 
> you want:
>
> s.send(bytes("PRIVMSG " + channel + " :" + mess + "\n", "UTF-8"))
>
> (Try printing out the line you want to send before sending it, and 
> compare it with the example commands in the RFC.)
>
Thanks Rhodri, indeed it missed the colon.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread Chris Angelico
On Tue, Apr 2, 2019 at 7:11 AM John Doe  wrote:
>
> On 2019-04-01, Chris Angelico  wrote:
> >
> > Cool. Please don't post context-free messages though - not everyone
> > knows that you were talking about IRC. (Part of that is because your
> > subject line didn't mention IRC either.)
> >
> I've mentioned it in a mother post mate.

Not everyone sees every post, for various reasons. So it's best to
include at least a bit of context in your replies.

> > If you're going to do a lot with IRC, I would recommend either picking
> > up a dedicated IRC library, or reading up on the protocol. You'll need
> > to understand the exact limitations and restrictions, how to properly
> > escape things, etc, etc, etc, if you're going to talk over a plain
> > socket. It's not a difficult protocol to use, but you should learn its
> > subtleties. (Or just grab a library.)
> >
> I don't know im a lot, it's just a training, I've created some script
> and just of curiosity checking option of sending messages.
>

Sure. You'll still need to sort out some parsing though; you can never
depend on exactly how much content you get back from a single socket
read.

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


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, Chris Angelico  wrote:
>
> Cool. Please don't post context-free messages though - not everyone
> knows that you were talking about IRC. (Part of that is because your
> subject line didn't mention IRC either.)
>
I've mentioned it in a mother post mate.

> If you're going to do a lot with IRC, I would recommend either picking
> up a dedicated IRC library, or reading up on the protocol. You'll need
> to understand the exact limitations and restrictions, how to properly
> escape things, etc, etc, etc, if you're going to talk over a plain
> socket. It's not a difficult protocol to use, but you should learn its
> subtleties. (Or just grab a library.)
>
I don't know im a lot, it's just a training, I've created some script
and just of curiosity checking option of sending messages.

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


Re: Losing words

2019-04-01 Thread Chris Angelico
On Tue, Apr 2, 2019 at 6:36 AM John Doe  wrote:
>
> On 2019-04-01, Roel Schroeven  wrote:
> > This is what 'while' is made for:
> >
> > def text():
> >  while True:
> >  mess = input("> ")
> >  s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n",
> > "UTF-8"))
> >
>
>  see it working thanks, indeed while is powerful, had to add colon to be able 
> send a whole string but can
>  get it working with other loop while 1, I tried many ways to implement
>  it together but either I cant send or receive and print data from
>  someone sending datas to channel.
>
> def text():
> while True:
> mess = input("> ")
> print(mess)
> s.send(bytes("PRIVMSG " + " "+ channel + " " + ":" + mess  + "\n", 
> "UTF-8"))
>
> text()
>
> while 1:
> data = s.recv(4096).decode('utf-8')
> print(data)
> if data.find('PING') != -1:
> s.send(str('PONG ' + data.split(':')[1] + '\r\n').encode())
> print('PONG sent \n')
>

Yeah, definitely get to know the protocol or get a library. You cannot
depend on a single socket read representing a single message. You'll
need to properly parse the incoming stream; otherwise, you'll run into
other problems, like "my messages don't work if two of them come in at
the same time". There are IRC libraries on PyPI.

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


Re: Losing words

2019-04-01 Thread Chris Angelico
On Tue, Apr 2, 2019 at 6:31 AM John Doe  wrote:
>
>
> The colon was the solution, thanks.
>

Cool. Please don't post context-free messages though - not everyone
knows that you were talking about IRC. (Part of that is because your
subject line didn't mention IRC either.)

If you're going to do a lot with IRC, I would recommend either picking
up a dedicated IRC library, or reading up on the protocol. You'll need
to understand the exact limitations and restrictions, how to properly
escape things, etc, etc, etc, if you're going to talk over a plain
socket. It's not a difficult protocol to use, but you should learn its
subtleties. (Or just grab a library.)

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


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, Roel Schroeven  wrote:
> This is what 'while' is made for:
>
> def text():
>  while True:
>  mess = input("> ")
>  s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", 
> "UTF-8"))
>

 see it working thanks, indeed while is powerful, had to add colon to be able 
send a whole string but can
 get it working with other loop while 1, I tried many ways to implement
 it together but either I cant send or receive and print data from
 someone sending datas to channel.

def text():
while True:
mess = input("> ")
print(mess)
s.send(bytes("PRIVMSG " + " "+ channel + " " + ":" + mess  + "\n", 
"UTF-8"))

text()

while 1:
data = s.recv(4096).decode('utf-8')
print(data)
if data.find('PING') != -1:
s.send(str('PONG ' + data.split(':')[1] + '\r\n').encode())
print('PONG sent \n')

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


Re: Losing words

2019-04-01 Thread Abdur-Rahmaan Janhangeer
Since this is IRC, you might want to see a demo here:
https://github.com/Abdur-rahmaanJ/honeybot/blob/master/honeybot/main.py

Abdur-Rahmaan Janhangeer
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread John Doe


The colon was the solution, thanks.

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


Re: Python Remote Work

2019-04-01 Thread Abdur-Rahmaan Janhangeer
Maybe add your field

web? data science? machine learning? automation? computer vision? ...

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Python Remote Work

2019-04-01 Thread Shane
Hi,

Bit of a long shot! I am looking for remote work and like the look of Python.

I am an Australian, with a degree in Commercial computing, with 15 years using 
Delphi in a business environment.

I am looking for a company to X train me to Python remotely, or maybe even a 
remote Python developer with too much work on his/her plate that wants some 
paid help and is willing to point me in the right direction.

cheers

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


Re: Losing words

2019-04-01 Thread Roel Schroeven

John Doe schreef op 1/04/2019 om 19:16:

On 2019-04-01, Joel Goldstick  wrote:


def text():
 mess = input("> ")
 s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", "UTF-8"))

 text()



Is this a typo or are you calling text() from within text()?



Indeed I do :-)
I was thinking on another way but nothing came up to me but guess what?
It works. What else I could do?


This is what 'while' is made for:

def text():
while True:
mess = input("> ")
s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", 
"UTF-8"))



The recursive solution you used works at first but stops working with 
RecursionError when the maximum recursion depth is exceeded.



--
"Honest criticism is hard to take, particularly from a relative, a
friend, an acquaintance, or a stranger."
-- Franklin P. Jones

Roel Schroeven

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


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, Chris Angelico  wrote:
>
> Use a loop, not recursion :)
>
I can guess only you mean: while but I've got no idea while what.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread MRAB

On 2019-04-01 18:16, John Doe wrote:

On 2019-04-01, Joel Goldstick  wrote:


def text():
mess = input("> ")
s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", "UTF-8"))

text()



Is this a typo or are you calling text() from within text()?



Indeed I do :-)
I was thinking on another way but nothing came up to me but guess what?
It works. What else I could do?


It'll work until it reaches the Python stack reaches its limit.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread Chris Angelico
On Tue, Apr 2, 2019 at 4:21 AM John Doe  wrote:
>
> On 2019-04-01, Joel Goldstick  wrote:
> >>
> >> def text():
> >> mess = input("> ")
> >> s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", "UTF-8"))
> >>
> >> text()
> >>
> >
> > Is this a typo or are you calling text() from within text()?
> >>
> Indeed I do :-)
> I was thinking on another way but nothing came up to me but guess what?
> It works. What else I could do?

Use a loop, not recursion :)

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


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, Joel Goldstick  wrote:
>>
>> def text():
>> mess = input("> ")
>> s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", "UTF-8"))
>>
>> text()
>>
>
> Is this a typo or are you calling text() from within text()?
>>
Indeed I do :-) 
I was thinking on another way but nothing came up to me but guess what?
It works. What else I could do?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread Grant Edwards
On 2019-04-01, Rhodri James  wrote:

 I'm learning SOCKETS and working with Irc.
   ---
   s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
   
   When more than one word ( for example: This is a message)
   in *message* it sends the FIRST word only "This" and skips the rest.

One problem appears to be that you're observing some behavior other
than what you expect (you see X when you expect Y).  You then jump to
the conclusion that your app is sending A instead of B.

   Any ideas how to solve the problem? I was seating on it on the night
   but nothing came up.

Two bits of advice:

1) When asking for help, describe the unexpected behavior
   _that_you_actually_see_ not an unconfirmed underlying problem that
   you've assumed is causing that unexpected behavior.

2) If you think your app is sending A instead of B, then use a tool
   like wireshark to determine what your app is actually sending.

> (Try printing out the line you want to send before sending it, and 
> compare it with the example commands in the RFC.)

What he said!  Adding a few print() calls can shed a _lot_ of light on
a problem.

Also: if reading the RFC doesn't help, use wireshark to compare
behavior of an app that works with yours.

-- 
Grant Edwards   grant.b.edwardsYow! I am a jelly donut.
  at   I am a jelly donut.
  gmail.com

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


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, Jon Ribbens  wrote:
> On 2019-04-01, John Doe  wrote:
>> I'm learning SOCKETS and working with Irc.
>>  ---
>>  s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
>>  
>>  When more than one word ( for example: This is a message) 
>>  in *message* it sends the FIRST word only "This" and skips the rest.
>>  Any ideas how to solve the problem? I was seating on it on the night
>>  but nothing came up.
>
> Your problem isn't with Python (although as others have mentioned you
> should be using .sendall not .send) but with the IRC protocol - you
> need to prefix the message with a ':'. Also technically you should
> be using '\r\n' not '\n' at the end but I should imagine most servers
> don't care.

sendall also is not sending a whole sentence. I used to have '\r\n' as
well no changes in sending a string at all then must be as you're saying
that most don't care.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread Rhodri James

On 01/04/2019 16:14, John Doe wrote:

On 2019-04-01, Chris Angelico  wrote:


I'm learning SOCKETS and working with Irc.
  ---
  s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
  
  When more than one word ( for example: This is a message)
  in *message* it sends the FIRST word only "This" and skips the rest.
  Any ideas how to solve the problem? I was seating on it on the night
  but nothing came up.


Does your message begin with a colon?

You may need a lot more context here. I have no idea what you're
running into because one line of code is vastly insufficient.



Nah mate,

def text():
 mess = input("> ")
 s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", "UTF-8"))

 text()

-
   
> This is a message


and it sends just first word in this example: "This".


I'm not an expert, but looking at RFC-1459 it looks like your final 
parameter (the message) needs to be preceded by a colon.  In other words 
you want:


s.send(bytes("PRIVMSG " + channel + " :" + mess + "\n", "UTF-8"))

(Try printing out the line you want to send before sending it, and 
compare it with the example commands in the RFC.)


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread Jon Ribbens
On 2019-04-01, John Doe  wrote:
> I'm learning SOCKETS and working with Irc.
>  ---
>  s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
>  
>  When more than one word ( for example: This is a message) 
>  in *message* it sends the FIRST word only "This" and skips the rest.
>  Any ideas how to solve the problem? I was seating on it on the night
>  but nothing came up.

Your problem isn't with Python (although as others have mentioned you
should be using .sendall not .send) but with the IRC protocol - you
need to prefix the message with a ':'. Also technically you should
be using '\r\n' not '\n' at the end but I should imagine most servers
don't care.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread Joel Goldstick
On Mon, Apr 1, 2019 at 11:16 AM John Doe  wrote:
>
> On 2019-04-01, Chris Angelico  wrote:
> >>
> >> I'm learning SOCKETS and working with Irc.
> >>  ---
> >>  s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
> >>  
> >>  When more than one word ( for example: This is a message)
> >>  in *message* it sends the FIRST word only "This" and skips the rest.
> >>  Any ideas how to solve the problem? I was seating on it on the night
> >>  but nothing came up.
> >
> > Does your message begin with a colon?
> >
> > You may need a lot more context here. I have no idea what you're
> > running into because one line of code is vastly insufficient.
> >
>
> Nah mate,
>
> def text():
> mess = input("> ")
> s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", "UTF-8"))
>
> text()
>

Is this a typo or are you calling text() from within text()?
>-
>
>> This is a message
>
>and it sends just first word in this example: "This".
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Syntax for one-line "nonymous" functions in "declaration style"

2019-04-01 Thread Schachner, Joseph
Re: ">> Neither i like how a function magically turns into a generator if the 
>> keyword `yield` appears somewhere within its definition.

> I agree, there should have been a required syntactic element on the "def"
> line as well to signal it immediately to the reader. It won't stop me from 
> using them, though."

One way to save people looking at the code from having to look through a 
function for a yield statement to see if it is a generator would be to add a 
"""doc string""" immediately after the function def, saying that it is a 
generator
and describing what it does.  I realize I'm calling on the programmer to 
address this issue by adding doc strings.  Nonetheless adding doc strings is a 
good habit to get in to.
--- Joseph S.
-Original Message-
From: Ian Kelly  
Sent: Sunday, March 31, 2019 3:45 PM
To: Python 
Subject: Re: Syntax for one-line "nonymous" functions in "declaration style"

On Sun, Mar 31, 2019 at 1:09 PM Alexey Muranov 
wrote:
>
> On dim., Mar 31, 2019 at 6:00 PM, python-list-requ...@python.org wrote:
> > On Sat, Mar 30, 2019, 5:32 AM Alexey Muranov 
> > 
> > wrote:
> >
> >>
> >>  On ven., Mar 29, 2019 at 4:51 PM, python-list-requ...@python.org
> >> wrote:
> >>  >
> >>  > There could perhaps be a special case for lambda expressions 
> >> such  >  that,  > when they are directly assigned to a variable, 
> >> Python would use the  > variable name as the function name. I 
> >> expect this could be  >  accomplished by  > a straightforward 
> >> transformation of the AST, perhaps even by just  >  replacing  > 
> >> the assignment with a def statement.
> >>
> >>  If this will happen, that is, if in Python assigning a 
> >> lambda-defined  function to a variable will mutate the function's 
> >> attributes, or else,  if is some "random" syntactically-determined 
> >> cases
> >>
> >>  f = ...
> >>
> >>  will stop being the same as evaluating the right-hand side and  
> >> assigning the result to "f" variable, it will be a fairly good 
> >> extra  reason for me to go away from Python.
> >>
> >
> > Is there a particular reason you don't like this? It's not too 
> > different from the syntactic magic Python already employs to support 
> > the 0-argument form of super().
>
> I do not want any magic in a programming language i use, especially if 
> it breaks simple rules.
>
> I do not like 0-argument `super()` either, but at least I do not have 
> to use it.

Well, you wouldn't have to use my suggestion either, since it only applies to 
assignments of the form "f = lambda x: blah". As has already been stated, the 
preferred way to do this is with a def statement. So just use a def statement 
for this, and it wouldn't affect you (unless you *really* want the function's 
name to be "" for some reason).

That said, that's also the reason why this probably wouldn't happen. Why go to 
the trouble of fixing people's lambda assignments for them when the preferred 
fix would be for them to do it themselves by replacing them with def statements?

> Neither i like how a function magically turns into a generator if the 
> keyword `yield` appears somewhere within its definition.

I agree, there should have been a required syntactic element on the "def"
line as well to signal it immediately to the reader. It won't stop me from 
using them, though.

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


Re: python os.chdir() Windows Error 2

2019-04-01 Thread Calvin Spealman
What are you actually trying to do?

os.chdir() simply changes the current working directory of your process. It
doesn't read any data or "import" or really have any affect on its own. The
current directory is the directory you ran the script from in the first
place, which is where files will be opened from. os.chdir() changes that
directory, affecting future files you access with open(), but doesn't have
a direct effect. Multiple chdir() calls in a row would simply be
meaningless.

On Mon, Apr 1, 2019 at 11:45 AM  wrote:

> Hey guys,
>
> I´ve got a problem importing a file with os.chdir. I´ve done a lot of
> research but still I can´t fix it. For any suggestions I would be so
> thankful!
>
> This is what I´ve tried so far:
>
> import os
> import numpy as np
> import matplotlib.pyplot as plt
>
>
> os.chdir('C:\Users\Ayla\Documents\Uni\Master_Umweltingenieurwesen\Study_Project\kerschbaum_input')
>
> os.chdir('C:\\Users\Ayla\Documents\Uni\Master_Umweltingenieurwesen\Study_Project\kerschbaum_input')
>
> os.chdir('C:\\Users\\Ayla\\Documents\\Uni\\Master_Umweltingenieurwesen\\Study_Project\\kerschbaum_input')
>
> os.chdir('C:/Users/Ayla/Documents/Uni/Master_Umweltingenieurwesen/Study_Project/kerschbaum_input')
>
> os.chdir('C://Users/Ayla/Documents/Uni/Master_Umweltingenieurwesen/Study_Project/kerschbaum_input')
>
> os.chdir('C://Users//Ayla//Documents//Uni/vMaster_Umweltingenieurwesen//Study_Project//kerschbaum_input')
>
> and each of these with [r'C:..'], " instead of ', and \\?\c instead of C.
> I also added the path (in advanced system settings) of the folder.
>
> Best regards
> Ayla
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 

CALVIN SPEALMAN

SENIOR QUALITY ENGINEER

cspea...@redhat.com  M: +1.336.210.5107

TRIED. TESTED. TRUSTED. 
-- 
https://mail.python.org/mailman/listinfo/python-list


python os.chdir() Windows Error 2

2019-04-01 Thread grossmudda
Hey guys, 

I´ve got a problem importing a file with os.chdir. I´ve done a lot of research 
but still I can´t fix it. For any suggestions I would be so thankful!

This is what I´ve tried so far:

import os
import numpy as np
import matplotlib.pyplot as plt

os.chdir('C:\Users\Ayla\Documents\Uni\Master_Umweltingenieurwesen\Study_Project\kerschbaum_input')
os.chdir('C:\\Users\Ayla\Documents\Uni\Master_Umweltingenieurwesen\Study_Project\kerschbaum_input')
os.chdir('C:\\Users\\Ayla\\Documents\\Uni\\Master_Umweltingenieurwesen\\Study_Project\\kerschbaum_input')
os.chdir('C:/Users/Ayla/Documents/Uni/Master_Umweltingenieurwesen/Study_Project/kerschbaum_input')
os.chdir('C://Users/Ayla/Documents/Uni/Master_Umweltingenieurwesen/Study_Project/kerschbaum_input')
os.chdir('C://Users//Ayla//Documents//Uni/vMaster_Umweltingenieurwesen//Study_Project//kerschbaum_input')

and each of these with [r'C:..'], " instead of ', and \\?\c instead of C.
I also added the path (in advanced system settings) of the folder.

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


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, David Raymond  wrote:
> https://docs.python.org/3.7/library/socket.html#socket.socket.send
>
> .send returns the number of bytes that it actually succeeded in sending. From 
> the docs: "Applications are responsible for checking that all data has been 
> sent; if only some of the data was transmitted, the application needs to 
> attempt delivery of the remaining data."
>
> You could also switch to using .sendall, which will do retries for you.
>
> But in either case you get a return code which lets you know if everything 
> went through ok.

Tried *sendall* and same result just first word was sent.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread John Doe
On 2019-04-01, Chris Angelico  wrote:
>>
>> I'm learning SOCKETS and working with Irc.
>>  ---
>>  s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
>>  
>>  When more than one word ( for example: This is a message)
>>  in *message* it sends the FIRST word only "This" and skips the rest.
>>  Any ideas how to solve the problem? I was seating on it on the night
>>  but nothing came up.
>
> Does your message begin with a colon?
>
> You may need a lot more context here. I have no idea what you're
> running into because one line of code is vastly insufficient.
>

Nah mate, 

def text():
mess = input("> ")
s.send(bytes("PRIVMSG " + " "+ channel + " " +  mess  + "\n", "UTF-8"))

text()

   -
  
   > This is a message

   and it sends just first word in this example: "This". 

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


RE: Losing words

2019-04-01 Thread David Raymond
https://docs.python.org/3.7/library/socket.html#socket.socket.send

.send returns the number of bytes that it actually succeeded in sending. From 
the docs: "Applications are responsible for checking that all data has been 
sent; if only some of the data was transmitted, the application needs to 
attempt delivery of the remaining data."

You could also switch to using .sendall, which will do retries for you.

But in either case you get a return code which lets you know if everything went 
through ok.


-Original Message-
From: Python-list 
[mailto:python-list-bounces+david.raymond=tomtom@python.org] On Behalf Of 
John Doe
Sent: Monday, April 01, 2019 9:39 AM
To: python-list@python.org
Subject: Losing words

I'm learning SOCKETS and working with Irc.
 ---
 s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
 
 When more than one word ( for example: This is a message) 
 in *message* it sends the FIRST word only "This" and skips the rest.
 Any ideas how to solve the problem? I was seating on it on the night
 but nothing came up.
-- 
https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Losing words

2019-04-01 Thread Chris Angelico
On Tue, Apr 2, 2019 at 12:41 AM John Doe  wrote:
>
> I'm learning SOCKETS and working with Irc.
>  ---
>  s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
>  
>  When more than one word ( for example: This is a message)
>  in *message* it sends the FIRST word only "This" and skips the rest.
>  Any ideas how to solve the problem? I was seating on it on the night
>  but nothing came up.

Does your message begin with a colon?

You may need a lot more context here. I have no idea what you're
running into because one line of code is vastly insufficient.

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


Losing words

2019-04-01 Thread John Doe
I'm learning SOCKETS and working with Irc.
 ---
 s.send(bytes("PRIVMSG " + channel +" "+ message + "\n", "UTF-8"))
 
 When more than one word ( for example: This is a message) 
 in *message* it sends the FIRST word only "This" and skips the rest.
 Any ideas how to solve the problem? I was seating on it on the night
 but nothing came up.
-- 
https://mail.python.org/mailman/listinfo/python-list