Re: [Tutor] class functions/staticmethod?

2019-08-12 Thread Peter Otten
James Hartley wrote:

> I am lacking in understanding of the @staticmethod property.
> Explanation(s)/links might be helpful.  I have not found the descriptions
> found in the Internet wild to be particularly instructive.  Given the code
> below:
> =8<--
> from collections import namedtuple
> 
> class Foo():
> Dimensions = namedtuple('Dimensions', ['height', 'width'])
> _dimensions = Dimensions(3, 4)
> 
> def dimensions():
> print('id = {}'.format(id(Foo._dimensions)))
> return Foo._dimensions

That works with the class as Foo.dimensions is just a function in Python 3, 
but not with an instance because Python will try to pass the instance as the 
first argument

>>> Foo.dimensions()
id = 140192821560880
Dimensions(height=3, width=4)
>>> Foo().dimensions()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: dimensions() takes 0 positional arguments but 1 was given

You can turn it into a static method

@staticmethod
def dimensions():
print('id = {}'.format(id(Foo._dimensions)))
return Foo._dimensions

>>> Foo.dimensions()
id = 139629779179056
Dimensions(height=3, width=4)
>>> Foo().dimensions()
id = 139629779179056
Dimensions(height=3, width=4)

or, when you are planning for subclases, into a classmethod:

$ cat staticmethod_demo.py
class Foo():
_dimensions = "foo-dimensions"

@classmethod
def class_dimensions(cls):
return cls._dimensions

@staticmethod
def static_dimensions():
return Foo._dimensions


class Bar(Foo):
_dimensions = "bar-dimensions"
$ python3 -i staticmethod_demo.py 
>>> Foo.class_dimensions(), Foo.static_dimensions()
('foo-dimensions', 'foo-dimensions')
>>> Bar.class_dimensions(), Bar.static_dimensions()
('bar-dimensions', 'foo-dimensions')

> 
> @staticmethod
> def dimensions1():
> print('id = {}'.format(id(_dimensions)))
> return _dimensions
> =8<--
> The class method Foo.dimensions() is capable of accessing class members,
> but Foo.dimensions1() cannot. What does the @staticmethod decorator really
> add?

You do not really need static methods; they work like module-level 
functions. They are more of a means to organize your code; by writing

class Foo:
   @staticmethod
   def bar(...): 
   do stuff

instead of

def foo_bar(...):
do stuff

class Foo:
pass

you make the mental association between the class and the function a bit 
stronger.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class functions/staticmethod?

2019-08-12 Thread Steven D'Aprano
On Sun, Aug 11, 2019 at 10:58:37PM -0500, James Hartley wrote:
> I am lacking in understanding of the @staticmethod property.
> Explanation(s)/links might be helpful.  I have not found the descriptions
> found in the Internet wild to be particularly instructive.  Given the code
> below:
[...]
> The class method Foo.dimensions() is capable of accessing class members,
> but Foo.dimensions1() cannot. What does the @staticmethod decorator really
> add?

Very little.

To understand staticmethod in Python, you have to understand what 
ordinary methods do.

When you make a class with a method:

class MyClass(object):
def spam(self):
print(self)


the interpreter creates a plain old regular function called "spam", and 
attaches it to MyClass. It is precisely the same as doing this:

def spam(self):
print(self)

class MyClass(object):
pass

MyClass.spam = spam

except more convenient. Methods are actually regular functions under 
the hood. But when you access a method, like this:

instance = MyClass()
instance.spam()  # call the method

the interpreter does some runtime magic to convert the function object 
into a method object which automatically knows what "self" is. This 
magic is called "the descriptor protocol", it's very clever but advanced 
programming, and the details aren't important here.

So just think of it like this:

When you access instance.spam, the interpreter converts the plain old 
dumb function object which has no idea what "self" is into a magical 
method object which does.

If you bypass the descriptor "magic", you can grab hold of the plain-old 
regular function:

py> instance = MyClass()
py> vars(type(instance))['spam']  # Bypass all the magic.


but it's dumb, and doesn't know what "self" is:

py> vars(type(instance))['spam']()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: spam() missing 1 required positional argument: 'self'


If you use normal attribute access, the function is turned into a method 
object that knows what "self" should be:

py> instance.spam  # Normal access.
>

py> instance.spam()  # "self" is automatically provided
<__main__.MyClass object at 0xb77e52ac>


So that's how methods work normally. But what if you don't want a method 
that understands "self", but a regular dumb-old function, but for some 
reason it needs to be attached to a class?

You can't use a regular function in the class body, because it will be 
automatically turned into a method on access, and for some reason you 
don't want that. You need a way to tell the interpreter "Don't convert 
this into a method with self, leave it as a regular function", and 
staticmethod is that way.

(To be pedantic, it doesn't actually leave it as a regular function, it 
converts it to a staticmethod object which behaves like a regular 
function. But that's a difference which normally makes no difference.)

So you can see, the niche for staticmethod is very, very narrow. You 
need something that is attached to a class, which you can call like a 
method, but you don't want it to receive "self" as the automatic first 
argument. That's pretty rare.

For a very long time, the only known use for staticmethod was in the 
tests checking that the staticmethod code worked correctly.

So that's what staticmethod does. It is occassionally useful, but not 
very often. Chances are, if you think you need one, you probably don't.

So why doesn't it work the way you expect? For that, read my next email.




-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class functions/staticmethod?

2019-08-12 Thread Steven D'Aprano
Part Two.

On Sun, Aug 11, 2019 at 10:58:37PM -0500, James Hartley wrote:


> from collections import namedtuple
> 
> class Foo():
> Dimensions = namedtuple('Dimensions', ['height', 'width'])
> _dimensions = Dimensions(3, 4)
> 
> def dimensions():
> print('id = {}'.format(id(Foo._dimensions)))
> return Foo._dimensions
> 
> @staticmethod
> def dimensions1():
> print('id = {}'.format(id(_dimensions)))
> return _dimensions

> The class method Foo.dimensions() is capable of accessing class members,

Foo.dimensions is *not* a class method; it is a regular method that is 
written badly, and only works by accident.

It *seems* to be okay because when you try it like this:

Foo.dimensions()  # call directly from the class object

you bypass some of the method magic, and get access to the regular 
function object, which in turn does a global lookup by name to find 
"Foo" and everything works from that point (although a bit slower than 
necessary).

But it doesn't work properly, because if you try to use it like this:

Foo().dimensions()  # call from an instance

you'll get an error that the method takes no arguments but one is 
supplied.

To fix this, we can make it a proper classmethod like this:

class Foo():
Dimensions = namedtuple('Dimensions', ['height', 'width'])
_dimensions = Dimensions(3, 4)

@classmethod
def dimensions(cls):
print('id = {}'.format(id(cls._dimensions)))
return cls._dimensions


and now both Foo.dimensions() and Foo().dimensions() will work 
correctly, and as a bonus it ought to be a little faster.


Part 3 to follow.



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class functions/staticmethod?

2019-08-12 Thread Steven D'Aprano
Part 3.


On Sun, Aug 11, 2019 at 10:58:37PM -0500, James Hartley wrote:


> from collections import namedtuple
> 
> class Foo():
> Dimensions = namedtuple('Dimensions', ['height', 'width'])
> _dimensions = Dimensions(3, 4)
> 
> def dimensions():
> print('id = {}'.format(id(Foo._dimensions)))
> return Foo._dimensions
> 
> @staticmethod
> def dimensions1():
> print('id = {}'.format(id(_dimensions)))
> return _dimensions


In part 2, I explained that we can re-write the dimensions() method to 
work correctly using the @classmethod decorator:

@classmethod
def dimensions(cls):
print('id = {}'.format(id(cls._dimensions)))
return cls._dimensions


Another benefit of doing this is that it will now work correctly in 
subclasses.

class Bar(Foo):  # inherit from Foo
_dimensions = (3, 4, 5, 6)  # Override the parent's "dimensions".


Using your definition, Bar.dimensions() will return Foo._dimensions 
instead of Bar._dimensions. But using the classmethod version works as 
expected.

So why doesn't the staticmethod version work correctly? Its all to do 
with the way variable names are resolved by the interpreter.

If you are used to Java, for example, you might expect that "class 
variables" (what Python calls "class attributes") are part of the scope 
for methods:


spam = 999  # Global variable spam.

class MyClass(object):
 spam = 1  # Class attribute ("variable") spam.

 def method(self):
 return spam

instance = MyClass()


If you are used to Java's rules, you would expect that instance.method() 
will return 1, but in Python it returns the global spam, 999.

To simplify a little, the scoping rules for Python are described by the 
LEGB rule:

- Local variables have highest priority;
- followed by variables in the Enclosing function scope (if any);
- followed by Global variables;
- and lastly Builtins (like `len()`, `zip()`, etc).

Notice that the surrounding class isn't included.[1] To access either 
instance attributes or class attributes, you have to explicitly say so:

 def method(self):
 return self.spam

This is deliberate, and a FAQ:

https://docs.python.org/3/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls


Using Java's scoping rules, the staticmethod would have worked:

@staticmethod
def dimensions1():
print('id = {}'.format(id(_dimensions)))
return _dimensions

because it would see the _dimensions variable in the class scope. But 
Python doesn't work that way. You would have to grab hold of the class 
from the global scope, then grab dimensions:

@staticmethod
def dimensions1():
_dimensions = Foo._dimensions
print('id = {}'.format(id(_dimensions)))
return _dimensions


If you are coming from a Java background, you may have been fooled by an 
unfortunate clash in terminology. A "static method" in Java is closer to 
a *classmethod* in Python, not a staticmethod.

The main difference being that in Java, class variables (attributes) 
are automatically in scope; in Python you have to access them through 
the "cls" parameter.



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] HELP PLEASE

2019-08-12 Thread Marissa Russo
Hello,

I am trying to figure out what is going on and why my output is saying 
“” instead of giving me a number. Please let me know if 
you see the error in my code!!

import math

def get_numbers():
print("This program will compute the mean and standard deviation")
file1 = input("Please enter the first filename: ")
file2 = input("Please enter the second filename: ")
x = open(file1, "r")
y = open(file2, "r")
nums = x.readlines()
nums2 = y.readlines()

return nums, nums2

def mean(nums):
for num in nums:
_sum += num
return _sum / len(nums)

def mean2(nums2):
for num in nums2:
_sum += nums2
return _sum / len(nums2)

def main():
data = get_numbers()

print("The mean of the first file is: ", mean)
print("The mean of the second file is: ", mean2)
main()

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Joel Goldstick
On Mon, Aug 12, 2019 at 1:22 PM Marissa Russo  wrote:
>
> Hello,
>
> I am trying to figure out what is going on and why my output is saying 
> “” instead of giving me a number. Please let me know if 
> you see the error in my code!!
>

Marissa, you have lots of problems here.  First, you should copy and
paste the complete traceback instead of the snippet you showed.
> import math
>
> def get_numbers():
> print("This program will compute the mean and standard deviation")
> file1 = input("Please enter the first filename: ")
> file2 = input("Please enter the second filename: ")
> x = open(file1, "r")
> y = open(file2, "r")
> nums = x.readlines()
> nums2 = y.readlines()
>
> return nums, nums2
>

Above. You are returning a string of all the data in your files.. is
that what you want?

> def mean(nums):
> for num in nums:
> _sum += num
> return _sum / len(nums)
>
Your traceback probably is complaining about _sum +=.  You can't add
to a variable that doesn't exists.  Maybe try _sum = 0 above your for
loop


> def mean2(nums2):
> for num in nums2:
> _sum += nums2
> return _sum / len(nums2)
>
> def main():
> data = get_numbers()

Ok, so you call a function which will return a tuple with two values
into data.  But you don't do anything with data

You might put this here:

m = mean(data[0])
m2 = mean2(data[1])

then print m and m2
>
> print("The mean of the first file is: ", mean)
> print("The mean of the second file is: ", mean2)
> main()
>

So, first, show the complete error message here.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Sithembewena L. Dube
In your calls to the `*print*` function, you  are not calling the `*mean*`
and `*mean2*` functions that you declared to calculate averages. So Python
sees you trying to concatenate two function objects to strings and is not
happy. That's one thing.

Secondly, your code could be refactored to define one `*mean*` function as
your functions do virtually the same thing. Then, you could just call it as
needed.

Thirdly, you could use the `*with*` keyword. See "7.2. Reading and Writing
Files" at https://docs.python.org/3/tutorial/inputoutput.html


Kind regards,
Sithembewena Dube


*Sent with Shift
*

On Mon, Aug 12, 2019 at 7:24 PM Marissa Russo 
wrote:

> Hello,
>
> I am trying to figure out what is going on and why my output is saying
> “” instead of giving me a number. Please let me know
> if you see the error in my code!!
>
> import math
>
> def get_numbers():
> print("This program will compute the mean and standard deviation")
> file1 = input("Please enter the first filename: ")
> file2 = input("Please enter the second filename: ")
> x = open(file1, "r")
> y = open(file2, "r")
> nums = x.readlines()
> nums2 = y.readlines()
>
> return nums, nums2
>
> def mean(nums):
> for num in nums:
> _sum += num
> return _sum / len(nums)
>
> def mean2(nums2):
> for num in nums2:
> _sum += nums2
> return _sum / len(nums2)
>
> def main():
> data = get_numbers()
>
> print("The mean of the first file is: ", mean)
> print("The mean of the second file is: ", mean2)
> main()
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Alan Gauld via Tutor
On 12/08/2019 17:54, Marissa Russo wrote:

> def mean(nums):
> for num in nums:
> _sum += num
> return _sum / len(nums)
> 
> def mean2(nums2):
> for num in nums2:
> _sum += nums2
> return _sum / len(nums2)
> 
> def main():
> data = get_numbers()
> 
> print("The mean of the first file is: ", mean)
> print("The mean of the second file is: ", mean2)

Notice that in the print statement you use the names
of the functions.
Python therefore evaluates those names and discovers
that they are functions, so that's what it tells you.

To get the values you need to call the functions,
which you do by adding parens to the name:

 print("The mean of the first file is: ", mean(data[0]) )
 print("The mean of the second file is: ", mean2(data[1]) )

That will then execute the functions

Which leads us to the next problem.
In both functions you have a line like:

_sum += num

But that expands to

_sum = _sum + num

Which means you are trying to get a value from _sum
before assigning any value. You need to initialize
_sum before using it like that.

_sum = 0

But better still would be to use the builtin sum method:

sum(nums)

So your mean function turns into:

def mean(nums):
   return( sum(nums)/len(nums))

But that leads to the next problem which is that your data
is still in string format, which is what you read from the
file with getlines().
You can convert it to integers using a list comprehension
inside your get_numbers function:

nums = [int(s) for s in nums]

which assumes the file is a list of numbers each on one line?

If you are not familiar with the list comprehension shortcut
you can do it longhand like this:

num_copy = []
for num in nums:
num_copy.append(int(num))
nums = num_copy

Incidentally, the two mean functions look identical
to me. What do you think is different other than
the names?

Finally, you could just use the mean() function defined in
the statistics library of the standard library.

import statistics as stats
...
 print("The mean of the first file is: ", stats.mean(data[0]) )
 ...

That should be enough to be getting on with.

Once you get those things done you could post again and
we might suggest some ways to tidy the code up a little.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Mats Wichmann
On 8/12/19 10:54 AM, Marissa Russo wrote:
> Hello,
> 
> I am trying to figure out what is going on and why my output is saying 
> “” instead of giving me a number. Please let me know if 
> you see the error in my code!!

to quickly illustrate the specific question you asked - you got comments
on other stuff already:


>>> def foo():
... return "string from foo()"
...
>>> print(foo)

>>> print(foo())
string from foo()
>>>


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Union

2019-08-12 Thread Jim
I was reading the docs for PySimpbleGUI here: 
https://pysimplegui.readthedocs.io/en/latest/#building-custom-windows


In the table of parameters for the Window() function for example the 
icon parameter the meaning is  Union[str, str] Can be either a filename 
or Base64 value.


What is the usage of "Union". I don't recall seeing anything like it before.

Thanks,  Jim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Union

2019-08-12 Thread Mats Wichmann
On 8/12/19 2:50 PM, Jim wrote:
> I was reading the docs for PySimpbleGUI here:
> https://pysimplegui.readthedocs.io/en/latest/#building-custom-windows
> 
> In the table of parameters for the Window() function for example the
> icon parameter the meaning is  Union[str, str] Can be either a filename
> or Base64 value.
> 
> What is the usage of "Union". I don't recall seeing anything like it
> before.

it's type annotation. Search here:

https://docs.python.org/3/library/typing.html


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Union

2019-08-12 Thread Jim

On 8/12/19 4:12 PM, Mats Wichmann wrote:

On 8/12/19 2:50 PM, Jim wrote:

I was reading the docs for PySimpbleGUI here:
https://pysimplegui.readthedocs.io/en/latest/#building-custom-windows

In the table of parameters for the Window() function for example the
icon parameter the meaning is  Union[str, str] Can be either a filename
or Base64 value.

What is the usage of "Union". I don't recall seeing anything like it
before.


it's type annotation. Search here:

https://docs.python.org/3/library/typing.html



OK, thanks.

Jim

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Re: HELP PLEASE

2019-08-12 Thread Alan Gauld via Tutor
Forwarding to tutorblist for info...



 Forwarded Message 
Subject:Re: [Tutor] HELP PLEASE
Date:   Mon, 12 Aug 2019 19:34:48 +0100
From:   Alan Gauld 
Reply-To:   alan.ga...@yahoo.co.uk
To: Marissa Russo 



On 12/08/2019 19:17, Marissa Russo wrote:
> I fixed some things up???


OK, But please use ReplyAll when responding to list mails otherwise
it just comes to me (or whoever posted) instead of the whole list.
(And I might be busy. at the time..)

> import math
>
> def get_numbers():
> print("This program will compute the mean and standard deviation")
> file1 = input("Please enter the first filename: ")
> file2 = input("Please enter the second filename: ")
> x = open(file1, "r")
> y = open(file2, "r")
> nums = x.readlines()
> nums2 = y.readlines()
>
> num_copy = []
> for num in nums:
> num_copy.append(float(num))
> nums = num_copy
>
> return nums

You are only returning one list of numbers. you need to convert nums2 as
well and then return both.


To save some typing convert the?? int conversion loop into a function:


def?? to_ints(strings):
?? num_copy = []
?? for num in nums:
 num_copy.append(float(num))

?? return num_copy

then call that on both list of strings.


 return to_ints(nums), to_ints(nums2)


> def mean():
> _sum = 0
> return(sum(nums)/len(nums))

Notice you don't pass any values to mean so you are relying on
the function seeing the values of nums outside the function
somewhere. It is beter where you passs in the values as you did originally:

def mean(numbers):




> def main():
> data = get_numbers()
> m = mean(data[0])
> m2 = mean2(data[1])

You call mean2() but don't have a mean2() function anymore.

You only need mean() so call it both times but with different input data.



> print("The mean of the first file is: ", m)
> print("The mean of the second file is: ", m2)
> main()
>
> This is now the output error:
> Traceback (most recent call last):
> File "/Applications/Python 3.7/exercises .py", line 34, in 
> main()
> File "/Applications/Python 3.7/exercises .py", line 30, in main
> m = mean(data[0])
> TypeError: mean() takes 0 positional arguments but 1 was given


See the comment above.

You removed the input parameter to the mean() function.

But then you call it as if it was still there. You must be consistent
between your function definitions and function calls..


You need to start thinking like the interpreter as you walk through the
code.
Think about what it knows at any given point and how the various functions
communicate?? - usually by storing intermediate results in variables. (Many
find it convenient to jot down the variables and their values as they walk
through the code, updating the values as they go). So check what those
variables contain - using print statements to debug it if necessary.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HELP PLEASE

2019-08-12 Thread Marissa Russo
This is my code:

import math

def get_numbers():
print("This program will compute the mean and standard deviation")
file1 = input("Please enter the first filename: ")
file2 = input("Please enter the second filename: ")
x = open(file1, "r")
y = open(file2, "r")
nums = x.readlines()
nums2 = y.readlines()

return nums, nums2

def to_ints(strings):
num_copy = []
for num in nums:
num_copy.append(float(num))
return num_copy

return to_ints(nums), to_ints(nums2)

def mean(nums):
_sum = 0
return(sum(nums)/len(nums))

def main():
data = get_numbers()
m = mean(data[0])
m2 = mean(data[1])
print("The mean of the first file is: ", m)
print("The mean of the second file is: ", m2)
main()


This is the output of my updated code:

Traceback (most recent call last):
  File "/Applications/Python 3.7/exercises .py", line 37, in 
main()
  File "/Applications/Python 3.7/exercises .py", line 33, in main
m = mean(data[0])
  File "/Applications/Python 3.7/exercises .py", line 29, in mean
return(sum(nums)/len(nums))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
> On Aug 12, 2019, at 12:54 PM, Marissa Russo  wrote:
> 
> Hello,
> 
> I am trying to figure out what is going on and why my output is saying 
> “” instead of giving me a number. Please let me know if 
> you see the error in my code!!
> 
> import math
> 
> def get_numbers():
>print("This program will compute the mean and standard deviation")
>file1 = input("Please enter the first filename: ")
>file2 = input("Please enter the second filename: ")
>x = open(file1, "r")
>y = open(file2, "r")
>nums = x.readlines()
>nums2 = y.readlines()
> 
>return nums, nums2
> 
> def mean(nums):
>for num in nums:
>_sum += num
>return _sum / len(nums)
> 
> def mean2(nums2):
>for num in nums2:
>_sum += nums2
>return _sum / len(nums2)
> 
> def main():
>data = get_numbers()
> 
>print("The mean of the first file is: ", mean)
>print("The mean of the second file is: ", mean2)
> main()
> 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] cgi module help

2019-08-12 Thread rmlibre
I have a question about the cgi module. 

I'm trying to retrieve post data as a nested dictionary from client
code. 

For instance:



"""client code"""
from requests import sessions
from datetime import datetime

session = sessions.Session()
date = str(datetime.now())
msg_id = 0001
message = {"metadata": {"date": date, "id": msg_id}}
session.post(data=message)



"""server cgi script"""
import cgi

form = cgi.FieldStorage()
metadata = form["metadata"]
print(metadata)
>>> ["date", "id"]

for item in form.list:
print(f"{item}\n{item.name}\n{item.value}\n")

>>> MiniFieldStorage('metadata', 'date')
>>> metadata 
>>> date
>>> 
>>> MiniFieldStorage('metadata', 'id')
>>> metadata
>>> id
>>> 


My issue is the FieldStorage class doesn't seem to store the values
within metadata, it only stores the key of each element within the
nested dictionary. And it constructs MiniFieldStorage objects with
attributes such as .name == "metadata" and .value == "date". 

But I need the actual values, not just the name of the element. Any idea
how I can maintain this nested structure and retrieve the data within a
nested dictionary in an elegant way?

Constraints: 
For simplicity, I omitted the actual payload which is also a nested
dictionary that goes two levels deep. I'm searching for a solution
that's extensible enough to include such fields as well.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Re: HELP PLEASE

2019-08-12 Thread Alan Gauld via Tutor
On 12/08/2019 19:35, Alan Gauld via Tutor wrote:

> To save some typing convert the?? int conversion loop into a function:
> 
> 
> def?? to_ints(strings):
> ?? num_copy = []
> ?? for num in nums:
>  num_copy.append(float(num))
> 
> ?? return num_copy
#

No idea where all the ? came from, however I made a bad error
in that code...

It should read:

def to_ints(strings):
num_copy = []
for num in strings:   # strings not nums!
num_copy.append(float(num))
return num_copy

Apologies.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor