Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80936 > unrolled thread

Re: How modules work in Python

Started byAbdul Abdul <abdul.sw84@gmail.com>
First post2014-11-17 01:41 +0100
Last post2014-11-20 09:53 -0700
Articles 9 — 7 participants

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: How modules work in Python Abdul Abdul <abdul.sw84@gmail.com> - 2014-11-17 01:41 +0100
    Re: How modules work in Python Larry Hudson <orgnut@yahoo.com> - 2014-11-18 00:14 -0800
      Re: How modules work in Python sohcahtoa82@gmail.com - 2014-11-18 12:59 -0800
        Re: How modules work in Python Larry Hudson <orgnut@yahoo.com> - 2014-11-18 23:44 -0800
          Re: How modules work in Python Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-11-19 22:32 +1100
          Re: How modules work in Python sohcahtoa82@gmail.com - 2014-11-19 11:00 -0800
            Re: How modules work in Python Chris Angelico <rosuav@gmail.com> - 2014-11-20 08:50 +1100
            Re: How modules work in Python Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2014-11-19 21:32 -0500
            Re: How modules work in Python Michael Torrie <torriem@gmail.com> - 2014-11-20 09:53 -0700

#80936 — Re: How modules work in Python

FromAbdul Abdul <abdul.sw84@gmail.com>
Date2014-11-17 01:41 +0100
SubjectRe: How modules work in Python
Message-ID<mailman.15925.1416184915.18130.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

Dave,

Thanks for your nice explanation. For your answer on one of my questions:

* Modules don't have methods. open is an ordinary function in the module.*

Isn't "method" and "function" used interchangeably? In other words, aren't
they the same thing? Or, Python has some naming conventions here?

Thanks.

On Sun, Nov 16, 2014 at 11:39 PM, Dave Angel <davea@davea.name> wrote:

> Abdul Abdul <abdul.sw84@gmail.com> Wrote in message:
> > Hello,
> >
> > I'm new to Python, and just have a small question, and thought you might
> have an idea on it.
>
> You should start any new thread with a specification of the
>  versions of software you're asking about.  Since you didn't,
>  I'll assume python version 2.7, PIL version 1.7, and Linux Ubuntu
>   version 14.04.
>
> >
> > I came across the following example that uses the Python Imaging Library
> (PIL):
>
> >
> > from PIL import Image
> > img = Image.open('xyz.jpg')
> >
> > I know that PIL is a module. And, I think that Image is also a module,
> especially we are importing it.
>
> PIL is a package, whuch means it's a module containing other
>  modules.,  and contains modules such as Image. But that syntax
>  "from PIL import Image" doesn't tell you that. Any type of name
>  defined in module PIL can be retrieved by the from
>  syntax.
>
> The way I can tell is either read the docs, or ask in the interpreter.
> from PIL import Image
> print type (Image)
>
> <type 'module'>
>
> That from syntax is roughly equivalent to
> import PIL
> Image = PIL.Image
>
> And the leading capital I would have made me guess it was a class.
>  Thus I checked, using type ()
>
> >
> > I also understood the Image,open() part, as it appears we are using the
> method open() from the Image module.
>
> Modules don't have methods. open is an ordinary function in the module.
>
> >
> > My question is, where did PIL go here?
>
> I don't understand the question.  By using the from syntax, you
>  avoided having PIL in your namespace. If you wanted, you could
>  have said. import PIL.  And used PIL.Image.open()
>
>  Can a module have another module inside it?
> >
> Yes
>
> >
> >
>
>
> --
> DaveA
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>

[toc] | [next] | [standalone]


#80999

FromLarry Hudson <orgnut@yahoo.com>
Date2014-11-18 00:14 -0800
Message-ID<SNGdnY6EVddWYvfJnZ2dnUU7-YWdnZ2d@giganews.com>
In reply to#80936
First, I'll repeat everybody else:  DON'T TOP POST!!!

On 11/16/2014 04:41 PM, Abdul Abdul wrote:
> Dave,
>
> Thanks for your nice explanation. For your answer on one of my questions:
>
> *Modules don't have methods. open is an ordinary function in the module.*
>
> Isn't "method" and "function" used interchangeably? In other words, aren't they the same thing?
> Or, Python has some naming conventions here?
>

You've already received answers to this, but a short example might clarify the difference:

#-------  Code  --------
#   Define a function
def func1():
     print('This is function func1()')

#   Define a class with a method
class Examp:
     def func2(self):
         print('This is method func2()')

#   Try them out
obj = Examp()      #  Create an object (an instance of class Examp)
func1()            #  Call the function
obj.func2()        #  Call the method through the object
func2()            #  Try to call the method directly -- Error!
#-------  /Code  --------

This code results in the following:

This is function func1()
This is method func2()
Traceback (most recent call last):
   File "fun-meth.py", line 14, in <module>
     func2()
NameError: name 'func2' is not defined

      -=- Larry -=-

[toc] | [prev] | [next] | [standalone]


#81012

Fromsohcahtoa82@gmail.com
Date2014-11-18 12:59 -0800
Message-ID<89161395-a817-4412-956f-28f7581f3269@googlegroups.com>
In reply to#80999
On Tuesday, November 18, 2014 12:14:15 AM UTC-8, Larry Hudson wrote:
> First, I'll repeat everybody else:  DON'T TOP POST!!!
> 
> On 11/16/2014 04:41 PM, Abdul Abdul wrote:
> > Dave,
> >
> > Thanks for your nice explanation. For your answer on one of my questions:
> >
> > *Modules don't have methods. open is an ordinary function in the module.*
> >
> > Isn't "method" and "function" used interchangeably? In other words, aren't they the same thing?
> > Or, Python has some naming conventions here?
> >
> 
> You've already received answers to this, but a short example might clarify the difference:
> 
> #-------  Code  --------
> #   Define a function
> def func1():
>      print('This is function func1()')
> 
> #   Define a class with a method
> class Examp:
>      def func2(self):
>          print('This is method func2()')
> 
> #   Try them out
> obj = Examp()      #  Create an object (an instance of class Examp)
> func1()            #  Call the function
> obj.func2()        #  Call the method through the object
> func2()            #  Try to call the method directly -- Error!
> #-------  /Code  --------
> 
> This code results in the following:
> 
> This is function func1()
> This is method func2()
> Traceback (most recent call last):
>    File "fun-meth.py", line 14, in <module>
>      func2()
> NameError: name 'func2' is not defined
> 
>       -=- Larry -=-

You COULD have something like this though:

# --- myModule.py ---
def myFunc():
    print 'myFunc'


# --- main.py ---
import myModule
myModule.myFunc()


In this case, myFunc LOOKS like a method when it is called from main.py, but it is still a function.

[toc] | [prev] | [next] | [standalone]


#81027

FromLarry Hudson <orgnut@yahoo.com>
Date2014-11-18 23:44 -0800
Message-ID<5badneHU4qn11_HJnZ2dnUU7-eednZ2d@giganews.com>
In reply to#81012
On 11/18/2014 12:59 PM, sohcahtoa82@gmail.com wrote:
> On Tuesday, November 18, 2014 12:14:15 AM UTC-8, Larry Hudson wrote:
>> First, I'll repeat everybody else:  DON'T TOP POST!!!
>>
>> On 11/16/2014 04:41 PM, Abdul Abdul wrote:
>>> Dave,
>>>
>>> Thanks for your nice explanation. For your answer on one of my questions:
>>>
>>> *Modules don't have methods. open is an ordinary function in the module.*
>>>
>>> Isn't "method" and "function" used interchangeably? In other words, aren't they the same thing?
>>> Or, Python has some naming conventions here?
>>>
>>
>> You've already received answers to this, but a short example might clarify the difference:
>>
>> #-------  Code  --------
>> #   Define a function
>> def func1():
>>       print('This is function func1()')
>>
>> #   Define a class with a method
>> class Examp:
>>       def func2(self):
>>           print('This is method func2()')
>>
>> #   Try them out
>> obj = Examp()      #  Create an object (an instance of class Examp)
>> func1()            #  Call the function
>> obj.func2()        #  Call the method through the object
>> func2()            #  Try to call the method directly -- Error!
>> #-------  /Code  --------
>>
>> This code results in the following:
>>
>> This is function func1()
>> This is method func2()
>> Traceback (most recent call last):
>>     File "fun-meth.py", line 14, in <module>
>>       func2()
>> NameError: name 'func2' is not defined
>>
>>        -=- Larry -=-
>
> You COULD have something like this though:
>
> # --- myModule.py ---
> def myFunc():
>      print 'myFunc'
>
>
> # --- main.py ---
> import myModule
> myModule.myFunc()
>
>
> In this case, myFunc LOOKS like a method when it is called from main.py, but it is still a function.
>

My purpose was to give a _simple_ example of the difference in the two terms:  that a function 
is called directly and a method is called through an object.

Your example may _look_ the same (it uses the same dot syntax), but here it is to resolve a 
namespace -- a module is not an object.  So yes, this is still a function and not a method.  But 
we're getting rather pedantic here.

      -=- Larry -=-

[toc] | [prev] | [next] | [standalone]


#81033

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2014-11-19 22:32 +1100
Message-ID<546c7fe0$0$12994$c3e8da3$5496439d@news.astraweb.com>
In reply to#81027
Larry Hudson wrote:

> Your example may look the same (it uses the same dot syntax), but here it
> is to resolve a namespace -- a module is not an object.  So yes, this is
> still a function and not a method.  But we're getting rather pedantic
> here.


But not pedantic enough. Modules are, in fact, objects. All values in Python
are objects, including classes themselves! But modules are merely instances
of ModuleType:


py> import types
py> isinstance(types, types.ModuleType)
True
py> print(types)
<module 'types' from '/usr/local/lib/python3.3/types.py'>



The *simple* answer is that when you define a function inside the body of a
class, Python "magically" turns it into a method. But the *pedantic* answer
has to do with the descriptor protocol, and that is quite pedantic indeed.

A *simplified* description of the pedantic answer:

    When you look up an attribute, say obj.attr, Python checks 
    whether the attribute has a __get__ method. If it does, 
    rather than return that object itself, Python returns the 
    result of calling __get__. Functions have a __get__ method,
    and so they are descriptors.  The __get__ method of functions
    returns a method object.


Here's an example. Let's define a class with a function inside it, and an
instance:

py> class X(object):
...     def method(self):
...         return "spam"
... 
py> instance = X()


If we look inside the class __dict__, we can see the original function:

py> X.__dict__['method']
<function X.method at 0xb7cc814c>


If we look at that function, we see it has a __get__ method:

py> f = X.__dict__['method']
py> f.__get__
<method-wrapper '__get__' of function object at 0xb7cc814c>


Calling that __get__ method returns a method object:

py> f.__get__(instance, X)
<bound method X.method of <__main__.X object at 0xb7bd65ec>>


which is what a normal attribute lookup does:

py> instance.method
<bound method X.method of <__main__.X object at 0xb7bd65ec>>


Now, the twist: when you store an object in the *instance* __dict__, the
descriptor protocol doesn't get invoked. So when you have a function in a
module, it is stored in the instance dictionary and looking up module.func
does not call __get__ and does not return a method, it just returns the
function.

The same thing applies to non-modules too. If you define a function inside
the body of a class, it is stored in the class __dict__, but if you store
it in the instance __dict__, it never gets converted to a method.


You can read up on descriptors here:

https://docs.python.org/3/howto/descriptor.html



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#81036

Fromsohcahtoa82@gmail.com
Date2014-11-19 11:00 -0800
Message-ID<caa76927-c865-4868-94ff-12ba4ff99bbc@googlegroups.com>
In reply to#81027
On Tuesday, November 18, 2014 11:44:53 PM UTC-8, Larry Hudson wrote:
> On 11/18/2014 12:59 PM, sohcah...@gmail.com wrote:
> > On Tuesday, November 18, 2014 12:14:15 AM UTC-8, Larry Hudson wrote:
> >> First, I'll repeat everybody else:  DON'T TOP POST!!!
> >>
> >> On 11/16/2014 04:41 PM, Abdul Abdul wrote:
> >>> Dave,
> >>>
> >>> Thanks for your nice explanation. For your answer on one of my questions:
> >>>
> >>> *Modules don't have methods. open is an ordinary function in the module.*
> >>>
> >>> Isn't "method" and "function" used interchangeably? In other words, aren't they the same thing?
> >>> Or, Python has some naming conventions here?
> >>>
> >>
> >> You've already received answers to this, but a short example might clarify the difference:
> >>
> >> #-------  Code  --------
> >> #   Define a function
> >> def func1():
> >>       print('This is function func1()')
> >>
> >> #   Define a class with a method
> >> class Examp:
> >>       def func2(self):
> >>           print('This is method func2()')
> >>
> >> #   Try them out
> >> obj = Examp()      #  Create an object (an instance of class Examp)
> >> func1()            #  Call the function
> >> obj.func2()        #  Call the method through the object
> >> func2()            #  Try to call the method directly -- Error!
> >> #-------  /Code  --------
> >>
> >> This code results in the following:
> >>
> >> This is function func1()
> >> This is method func2()
> >> Traceback (most recent call last):
> >>     File "fun-meth.py", line 14, in <module>
> >>       func2()
> >> NameError: name 'func2' is not defined
> >>
> >>        -=- Larry -=-
> >
> > You COULD have something like this though:
> >
> > # --- myModule.py ---
> > def myFunc():
> >      print 'myFunc'
> >
> >
> > # --- main.py ---
> > import myModule
> > myModule.myFunc()
> >
> >
> > In this case, myFunc LOOKS like a method when it is called from main.py, but it is still a function.
> >
> 
> My purpose was to give a _simple_ example of the difference in the two terms:  that a function 
> is called directly and a method is called through an object.
> 
> Your example may _look_ the same (it uses the same dot syntax), but here it is to resolve a 
> namespace -- a module is not an object.  So yes, this is still a function and not a method.  But 
> we're getting rather pedantic here.
> 
>       -=- Larry -=-

I only started reading this list about a month ago, and from what I've seen, being pedantic is pretty much par for the course.

[toc] | [prev] | [next] | [standalone]


#81045

FromChris Angelico <rosuav@gmail.com>
Date2014-11-20 08:50 +1100
Message-ID<mailman.16001.1416433844.18130.python-list@python.org>
In reply to#81036
On Thu, Nov 20, 2014 at 6:00 AM,  <sohcahtoa82@gmail.com> wrote:
> I only started reading this list about a month ago, and from what I've seen, being pedantic is pretty much par for the course.

Usually in a good way. :)

ChrisA

[toc] | [prev] | [next] | [standalone]


#81049

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2014-11-19 21:32 -0500
Message-ID<mailman.16003.1416450770.18130.python-list@python.org>
In reply to#81036
On Wed, 19 Nov 2014 11:00:28 -0800 (PST), sohcahtoa82@gmail.com declaimed
the following:


>I only started reading this list about a month ago, and from what I've seen, being pedantic is pretty much par for the course.

	Ignoring the pop-up bogie...
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#81092

FromMichael Torrie <torriem@gmail.com>
Date2014-11-20 09:53 -0700
Message-ID<mailman.16032.1416502432.18130.python-list@python.org>
In reply to#81036
On 11/19/2014 02:50 PM, Chris Angelico wrote:
> On Thu, Nov 20, 2014 at 6:00 AM,  <sohcahtoa82@gmail.com> wrote:
>> I only started reading this list about a month ago, and from what I've seen, being pedantic is pretty much par for the course.
> 
> Usually in a good way. :)

And often for good reason.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web