473,666 Members | 2,296 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

noob import question

OK, I have a very simple class here:

class Student:
"""Defines the student class"""

def __init__(self, lName, fName, mi):
self.lName = lName
self.fName = fName
self.mi = mi

Then I have a small script that I am using as a test:

from Student import *

s1 = Student("Brian" , "Smith", "N")

print s1.lName

This works as expected. However, if I change the import statement to:
import Student

I get an error:
TypeError: 'module' object is not callable

I have tried to look up what is going on, but I have not found
anything. Would it be possible for someone to take a minute and give
an explanation?

Thank you - your time is appreciated.

Brian
br***@brianandk ate.com


May 19 '06 #1
11 1496

Brian Blazer wrote:
OK, I have a very simple class here:

class Student:
"""Defines the student class"""

def __init__(self, lName, fName, mi):
self.lName = lName
self.fName = fName
self.mi = mi

Then I have a small script that I am using as a test:

from Student import *

s1 = Student("Brian" , "Smith", "N")

print s1.lName

This works as expected. However, if I change the import statement to:
import Student

I get an error:
TypeError: 'module' object is not callable

I have tried to look up what is going on, but I have not found
anything. Would it be possible for someone to take a minute and give
an explanation?

I take it you are getting the error on the line
s1 = Student("Brian" , "Smith", "N")

This is because when you use 'import Student', it loads the file
Student.py into a namespace called Student (unlike the 'from'
statement, which loads it into the main namespace). to access anything
from your Student module, prepend with Student. , so your line becomes:
s1 = Student.Student ("Brian", "Smith", "N")

Iain Thank you - your time is appreciated.

Brian
br***@brianandk ate.com


May 19 '06 #2
> I have tried to look up what is going on, but I have not found
anything. Would it be possible for someone to take a minute and give
an explanation?


The

from <module> import <*|nameslist>

syntax imports some or all names found in <module> into the current modules
namespace. Thus you can access your class.

But if you do

import <module>

you only get <module> in your current namespace. So you need to access
anything inside <module> by prefixing the expression. In your case, it is

Student.Student

If you only write Student, that in fact is the MODULE Student, which
explains the error message.

Now while this sounds as if the from <module> import * syntax is the way to
go, you should refrain from that until you really know what you are doing
(and you currently _don't_ know), as this can introduce subtle and
difficult to debug bugs. If you don't want to write long module-names, you
can alias them:

import <moduel-with-long-name> as <shortname>
And it seems as if you have some JAVA-background, putting one class in one
file called the same as the class. Don't do that, it's a stupid restriction
in JAVA and should be avoided in PYTHON.

Diez
May 19 '06 #3
Thank you for your responses. I had a feeling is had something to do
with a namespace issue but I wasn't sure.

You are right, I do come from a Java background. If it is poor form
to name your class file the same as your class, can I ask what the
standard is?

Thanks again,
Brian

On May 19, 2006, at 8:33 AM, Diez B. Roggisch wrote:
I have tried to look up what is going on, but I have not found
anything. Would it be possible for someone to take a minute and give
an explanation?


The

from <module> import <*|nameslist>

syntax imports some or all names found in <module> into the current
modules
namespace. Thus you can access your class.

But if you do

import <module>

you only get <module> in your current namespace. So you need to access
anything inside <module> by prefixing the expression. In your case,
it is

Student.Student

If you only write Student, that in fact is the MODULE Student, which
explains the error message.

Now while this sounds as if the from <module> import * syntax is
the way to
go, you should refrain from that until you really know what you are
doing
(and you currently _don't_ know), as this can introduce subtle and
difficult to debug bugs. If you don't want to write long module-
names, you
can alias them:

import <moduel-with-long-name> as <shortname>
And it seems as if you have some JAVA-background, putting one class
in one
file called the same as the class. Don't do that, it's a stupid
restriction
in JAVA and should be avoided in PYTHON.

Diez
--
http://mail.python.org/mailman/listinfo/python-list


May 19 '06 #4
Brian Blazer wrote:
Thank you for your responses. I had a feeling is had something to do
with a namespace issue but I wasn't sure.

You are right, I do come from a Java background. If it is poor form
to name your class file the same as your class, can I ask what the
standard is?


Consider python modules what packages are in JAVA - aggregations of related
classes. Only if your module grows to an unmanagable size, split it up into
two modules.

Diez
May 19 '06 #5
PA

On May 19, 2006, at 15:33, Diez B. Roggisch wrote:
And it seems as if you have some JAVA-background, putting one class in
one
file called the same as the class. Don't do that, it's a stupid
restriction
in JAVA and should be avoided in PYTHON.


Restrictive or not, what's so fundamentally devious in putting a class
declaration in a separate file whose name is that of the declared class
(class Queue -> Queue.py)?

Sounds like a handy way of organizing your code, no?

Cheers

--
PA, Onnay Equitursay
http://alt.textdrive.com/

May 19 '06 #6
"PA" <pe************ @gmail.com> wrote:
Restrictive or not, what's so fundamentally devious in putting a class
declaration in a separate file whose name is that of the declared class
(class Queue -> Queue.py)?
nothing.
Sounds like a handy way of organizing your code, no?


sure, if you prefer to do things that way.

the Python style guide (PEP 8) used to recommend naming a module that con-
tains only one class (plus support factories and other functions) after the class,
but now recommends using other names for the module, to avoid confusion.

for some reason, some people seem to treat the latest edition of each PEP as
a divine truth, and all earlier editions as works of the devil. I guess they reset
their brain before each svn update.

</F>

May 19 '06 #7
Brian Blazer wrote:
OK, I have a very simple class here:

class Student:
class Student(object) :
"""Defines the student class"""

def __init__(self, lName, fName, mi):
self.lName = lName
self.fName = fName
self.mi = mi
Do yourself a favour: use meaningful names.
Then I have a small script that I am using as a test:

from Student import *
So your module is named Student.py ? The common convention is to use
all_lower for modules, and CapNames for classes. BTW, unlike Java, the
common use is to group closely related classes and functions in a same
module.
s1 = Student("Brian" , "Smith", "N")

print s1.lName

This works as expected. However, if I change the import statement to:
import Student

I get an error:
TypeError: 'module' object is not callable
Of course. And that's one for the reason for naming modules all_lower
and classes CapNames.

With
from Student import *

you import all the names (well... not all, read the doc about this)
defined in the module Student directly in the current namespace. So,
since the module Student contains the class Student, in this current
namespace, the name Student refers to the class Student.

With
import Student

you import the module name Student in the current namespace. You can
then refer to names defined in module Student with the qualified name
module.name. So here, to refer to the class Student, you need to use the
qualified name Student.Student .

You wouldn't have such a confusion if your module was named students !-)

I have tried to look up what is going on, but I have not found
anything.


you could have done something like this:

import Student
print dir()
print dir(Student)
print type(Student)
del Student
from Student import *
print dir()
print dir(Student)
print type(Student)
Also, reading the doc migh help:
http://www.python.org/doc/2.4.2/tut/node8.html

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 19 '06 #8
Brian Blazer wrote:
<ot>
please, dont top-post, and edit out irrelevant material
</ot>
You are right, I do come from a Java background.


Then you may want to read this:
http://dirtsimple.org/2004/12/python-is-not-java.html

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 19 '06 #9
PA wrote:

On May 19, 2006, at 15:33, Diez B. Roggisch wrote:
And it seems as if you have some JAVA-background, putting one class in
one
file called the same as the class. Don't do that, it's a stupid
restriction
in JAVA and should be avoided in PYTHON.


Restrictive or not, what's so fundamentally devious in putting a class
declaration in a separate file whose name is that of the declared class
(class Queue -> Queue.py)?

Sounds like a handy way of organizing your code, no?


Not in Python. Python classes tend to be smaller than Java classes.
Also, Python, while fully OO, is not anal-retentive about putting
everything in classes - functions are fine too. Would you advocate
putting each function in its own file ?-) And finally, with Python's
file<->module equivalence, grouping related classes and functions in a
same module greatly simplify imports.

wrt/ naming, having the module named after the class (your example)
leads to confusions like the one experimented by the OP. FWIW, Zope2
uses this convention, and I found this confusing too.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 19 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1933
by: Dave Williams | last post by:
First off...total noob to VB. So far have learned a lot in 1.5 days and feel fairly comfortable at throwing screens up. However, I want to start writing forms that revolve around an access database. From what I have read to date it looks like VB can only display 1 record at a time. I suspect this is not the case. How easy is it to display 10 records at a time (in a table format) that can be scrolled up and down ? When the current...
1
1653
by: Raaijmakers, Vincent \(GE Infrastructure\) | last post by:
Question: my src path looks like this: src\root\sub1 src\root\sub2 My main code is in root, lets say main.py and there is also a lib.py. In sub1 there if foo1.py and sub2 foo2.py Sorry for the long introduction...please don't stop reading... :-(
1
1801
by: davestrike | last post by:
I am a noob to sql and asp programming. I am working on a db for the gaming squad I am a member of. One of the pages I created is a roster list of all the squad members. Part of this roster is listing each member's email address. What several people have asked of me is to make it so the email addresses can be clicked on to open their email programs, just as html allows the mailto function to work. Here is a copy of the coding I am...
2
1610
by: What nickname do you want? | last post by:
I want to provide secured acces to a MySQL database. This is what I've done. Firstly the relevant pages are in a folder to which Apache requires password authentication. Then I have an HTML page with a form to enter (MySQL) ID and password, which I POST to a PHP page which tries to connect to the MySQL database, and if so starts a session... $id = $_POST; $pass=$_POST; if ($connect=mysql_pconnect("localhost",$id,$pass) ) {
3
3221
by: mh | last post by:
So on most modules I import, I can access the .__file__ attribute to find the implementation. ie: >>> import time >>> time.__file__ '/data1/virtualpython/lib/python2.3/lib-dynload/timemodule.so' >>> import socket >>> socket.__file__ '/data1/virtualpython/lib/python2.3/socket.pyc' This doesn't work on the "thread" module:
4
1404
by: Brian Blais | last post by:
Hello, I am trying to organize some of my code, and am having a little trouble with the import logic. I find I often have something like: MyPackage/ Part1/ # wants to use functions in Common/ __init__.py # does "from MyClass1 import MyClass1", etc,... MyClass1.py MyClass1a.py # depends on MyClass1
1
1128
by: narpet | last post by:
Hello all... I have a (probably very) easy question for the SQL experts here... Lets say I have a table with the following rows and data: Name Nickname Middlename ------------------------------------------------ Rodney Rod Bob
3
1130
by: Richhpcnec | last post by:
I have two text strings that I have read from a text file. The text strings that I have read are the 8 characters each, 859c58d4 and 80434d43. I have assigned them the varible names of string1 and string2. This text strings in reality represent hex values. How do I convert these text strings into numerical (long integers perhaps) so that I might subtract one from the other? Please help a noob trying to learn VB6. Rich
0
957
by: Gary Herron | last post by:
Dan Yamins wrote: Because loading (and reloading) assigns values to variables (called binding a value in Python), but does not go on a hunt to find variables to *unbind*. Once a variable is bound to a value, it stays bound until something unbinds or rebinds it, and module loading does no such thing. But in fact you did *not* delete the module from memory. A module
0
8440
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8355
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8866
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8550
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8638
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6191
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2769
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2006
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.