Re: import question
On 20/11/2021 03.38, lucas wrote: > ok. all good advice. thank you for that. and with all that I've decided > what to do. > > I'm going to close off any server-side python access so that I don't expose > my server or the file system to vulnerabilities and/or wonton attacks. I am > building a site for education and what I will configure is allow students to > setup and save their projects on the server but only direct them to program > in client-side Brython, which is a javascript translation of python for > browsers, hence "Brython" or "browser python". my server will provide the > javascript files for Brython and its standard libraries and any processing of > the student's projects will be directly on the client-side. this way there > is no access to the server or cpu or memory management problems. the server > will simply server html and Brython-based text, i.e., static pages, to the > client browser and the browser will process and interact with the Brython > directly. > > overall, the server will stay secure and the students can learn python > through Brython. sound, right? Lucas Alternately, 'stand on the shoulders of giants' and consider https://pythontutor.com/visualize.html#mode=edit This has the additional value for your trainees of showing a visual execution of their code. They can see step-by-step how Python/the computer interprets their (?perfect) instruction and exactly where things fall-over - with-out the added complication/cognitive-load of having to master a debugger! If you're still determined to invest a lot of time, it looks as if Phil has invested a lot of time, more recently, in widening the range of languages, (which is perhaps why(?)) the system has fallen behind in Python release. -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: import question
ok. all good advice. thank you for that. and with all that I've decided what to do. I'm going to close off any server-side python access so that I don't expose my server or the file system to vulnerabilities and/or wonton attacks. I am building a site for education and what I will configure is allow students to setup and save their projects on the server but only direct them to program in client-side Brython, which is a javascript translation of python for browsers, hence "Brython" or "browser python". my server will provide the javascript files for Brython and its standard libraries and any processing of the student's projects will be directly on the client-side. this way there is no access to the server or cpu or memory management problems. the server will simply server html and Brython-based text, i.e., static pages, to the client browser and the browser will process and interact with the Brython directly. overall, the server will stay secure and the students can learn python through Brython. sound, right? Lucas -- https://mail.python.org/mailman/listinfo/python-list
Re: import question
On 11/18/21 21:00, Dan Stromberg wrote: On Thu, Nov 18, 2021 at 6:19 PM Chris Angelico wrote: On Fri, Nov 19, 2021 at 11:24 AM Dan Stromberg wrote: On Thu, Nov 18, 2021 at 12:21 PM Chris Angelico wrote: If you're trying to make a Python-in-Python sandbox, I recommend not. Instead, use an OS-level sandbox (a chroot, probably some sort of CPU usage limiting, etc), and use that to guard the entire Python process. Python-in-Python will basically *never* be secure. Good advice to not try to sandbox python. But chroot can sometimes be broken out of. It isn't a cure-all. That's true, but it's way better than attempting Python-in-Python sandboxing. In any case, all the options worth investigating will be at the OS level. (Or maybe higher, but I can't imagine it being practical to create individual VMs for each client who comes to the web site.) Actually, there are ports of CPython and Micropython that run inside a web browser over WASM. Going with one of these might be safer. indeed... see pyodide https://github.com/pyodide/pyodide -- https://mail.python.org/mailman/listinfo/python-list
Re: import question
On Fri, Nov 19, 2021 at 3:00 PM Dan Stromberg wrote: > > > On Thu, Nov 18, 2021 at 6:19 PM Chris Angelico wrote: >> >> On Fri, Nov 19, 2021 at 11:24 AM Dan Stromberg wrote: >> > >> > >> > On Thu, Nov 18, 2021 at 12:21 PM Chris Angelico wrote: >> >> >> >> If you're trying to make a Python-in-Python sandbox, I recommend not. >> >> Instead, use an OS-level sandbox (a chroot, probably some sort of CPU >> >> usage limiting, etc), and use that to guard the entire Python process. >> >> Python-in-Python will basically *never* be secure. >> > >> > >> > Good advice to not try to sandbox python. >> > >> > But chroot can sometimes be broken out of. It isn't a cure-all. >> > >> >> That's true, but it's way better than attempting Python-in-Python >> sandboxing. In any case, all the options worth investigating will be >> at the OS level. >> >> (Or maybe higher, but I can't imagine it being practical to create >> individual VMs for each client who comes to the web site.) > > > Actually, there are ports of CPython and Micropython that run inside a web > browser over WASM. Going with one of these might be safer. > Hmm, interesting point. I'd mentally ruled out the in-browser options since the performance hit is usually far too costly, but if this is basically an educational site, it MAY be sufficient (people won't need spectacular performance when they're just learning the basics). ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: import question
On Thu, Nov 18, 2021 at 6:19 PM Chris Angelico wrote: > On Fri, Nov 19, 2021 at 11:24 AM Dan Stromberg > wrote: > > > > > > On Thu, Nov 18, 2021 at 12:21 PM Chris Angelico > wrote: > >> > >> If you're trying to make a Python-in-Python sandbox, I recommend not. > >> Instead, use an OS-level sandbox (a chroot, probably some sort of CPU > >> usage limiting, etc), and use that to guard the entire Python process. > >> Python-in-Python will basically *never* be secure. > > > > > > Good advice to not try to sandbox python. > > > > But chroot can sometimes be broken out of. It isn't a cure-all. > > > > That's true, but it's way better than attempting Python-in-Python > sandboxing. In any case, all the options worth investigating will be > at the OS level. > > (Or maybe higher, but I can't imagine it being practical to create > individual VMs for each client who comes to the web site.) > Actually, there are ports of CPython and Micropython that run inside a web browser over WASM. Going with one of these might be safer. -- https://mail.python.org/mailman/listinfo/python-list
Re: import question
On Fri, Nov 19, 2021 at 11:24 AM Dan Stromberg wrote: > > > On Thu, Nov 18, 2021 at 12:21 PM Chris Angelico wrote: >> >> If you're trying to make a Python-in-Python sandbox, I recommend not. >> Instead, use an OS-level sandbox (a chroot, probably some sort of CPU >> usage limiting, etc), and use that to guard the entire Python process. >> Python-in-Python will basically *never* be secure. > > > Good advice to not try to sandbox python. > > But chroot can sometimes be broken out of. It isn't a cure-all. > That's true, but it's way better than attempting Python-in-Python sandboxing. In any case, all the options worth investigating will be at the OS level. (Or maybe higher, but I can't imagine it being practical to create individual VMs for each client who comes to the web site.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: import question
On 2021-11-17, lucas wrote: > are there any other ways to import a module or package other then > the "import" or "from...import..." statements? i ask because i'm > allowing programming on my web2py website and i don't want any > accessing packages like os or sys. Safely allowing people to enter/upload and then execute Python code is very difficult. From my brief research into that question a little while (a year or two) ago, the answer was that can't really be done in any general way. IIRC, some promising work was done in PyPy to address this problem, but the sandbox stuff never got moved to Py3? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: import question
On Thu, Nov 18, 2021 at 12:21 PM Chris Angelico wrote: > If you're trying to make a Python-in-Python sandbox, I recommend not. > Instead, use an OS-level sandbox (a chroot, probably some sort of CPU > usage limiting, etc), and use that to guard the entire Python process. > Python-in-Python will basically *never* be secure. > Good advice to not try to sandbox python. But chroot can sometimes be broken out of. It isn't a cure-all. -- https://mail.python.org/mailman/listinfo/python-list
Re: import question
On Fri, Nov 19, 2021 at 7:09 AM lucas wrote: > > hello one and all, > > are there any other ways to import a module or package other then the > "import" or "from...import..." statements? i ask because i'm allowing > programming on my web2py website and i don't want any accessing packages like > os or sys. > > thank you in advance and have a great day, lucas > Yes, there are many. For starters, the importlib module can do anything that importing can do, as can the __import__ function. Plus, with Python code, you could open the file, read from it, and exec it. There are myriad ways to fetch up code, and it's even possible to break out of a sandbox without ever using a single underscore. If you're trying to make a Python-in-Python sandbox, I recommend not. Instead, use an OS-level sandbox (a chroot, probably some sort of CPU usage limiting, etc), and use that to guard the entire Python process. Python-in-Python will basically *never* be secure. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
import question
hello one and all, are there any other ways to import a module or package other then the "import" or "from...import..." statements? i ask because i'm allowing programming on my web2py website and i don't want any accessing packages like os or sys. thank you in advance and have a great day, lucas -- https://mail.python.org/mailman/listinfo/python-list
Re: Module import question
On Aug 9, 2020 11:41 AM, "Mats Wichmann" wrote: > > On 8/9/20 12:51 AM, Gabor Urban wrote: > > Hi guys, > > > > I have a quite simple question but I could not find the correct answer. > > > > I have twoo modules A and B. A imports B. If I import A in a script, Will > > be B imported automatically? I guess not, but fő not know exactly. > > > > Thanks for your answer ín advance, > > Think of import as meaning "make available in namespace". Well it's actually a little more involved than that. When python import a module it executes the module code. This is why you often see at the bottom of a module: if __name__ == '__main__': # code to execute when running the module as opposed to importing it. When importing a module __name__ is the module's name rather than '__main__'. What happens when module A Imports module B depends on whether or not the import B statement is actually executed. -- https://mail.python.org/mailman/listinfo/python-list
Re: Module import question
Hi guys, Thanks for the answers. IT is clear Noé. Gábor -- https://mail.python.org/mailman/listinfo/python-list
Re: Module import question
On 8/9/20 12:51 AM, Gabor Urban wrote: > Hi guys, > > I have a quite simple question but I could not find the correct answer. > > I have twoo modules A and B. A imports B. If I import A in a script, Will > be B imported automatically? I guess not, but fő not know exactly. > > Thanks for your answer ín advance, Think of import as meaning "make available in namespace". If A simply imports B, then B is available in A's namespace as a name for module B's namespace, and you can access things inside B by qualifying the names: if Foo is in B, then B.Foo works, Foo does not. Different forms of the import statement change the way symbols are made available, e.g you can do from B import *# all the symbols from B are in A's global namespace, Foo works now import B as Baz# B is available through the name Baz, so use Baz.Foo etc. If you have a separate program, call it C, and it imports A, then A is available in C as a name for module A's namespace. That said nothing about B, so the symbol B is not available in C. But if C calls something in A that uses B, then that will work fine, because B exists in A's namespace. And you can access symbols from B by properly qualifying: A.B.Foo. Which is it you meant by "imported automatically"? See Byung-Hee's example to see this in action without all these messy words :) -- https://mail.python.org/mailman/listinfo/python-list
Re: Module import question
Gabor Urban writes: > Hi guys, > > I have a quite simple question but I could not find the correct answer. > > I have twoo modules A and B. A imports B. If I import A in a script, Will > be B imported automatically? I guess not, but fő not know exactly. > > Thanks for your answer ín advance, #+BEGIN_SRC: sh + python (bionic)soyeomul@localhost:~/222$ cat b.py name = "b" (bionic)soyeomul@localhost:~/222$ cat a.py import b name = "a" (bionic)soyeomul@localhost:~/222$ cat c.py import a print(a.name) # a.py's name print(a.b.name) # b.py's name (bionic)soyeomul@localhost:~/222$ python3 c.py a b (bionic)soyeomul@localhost:~/222$ #+END_SRC Sincerely, Byung-Hee -- ^고맙습니다 _白衣從軍_ 감사합니다_^))// -- https://mail.python.org/mailman/listinfo/python-list
Module import question
Hi guys, I have a quite simple question but I could not find the correct answer. I have twoo modules A and B. A imports B. If I import A in a script, Will be B imported automatically? I guess not, but fő not know exactly. Thanks for your answer ín advance, Gábor -- https://mail.python.org/mailman/listinfo/python-list
Re: trivial import question
On Wednesday, February 5, 2014 9:52:33 AM UTC-8, nevets...@gmail.com wrote: The underscore relative to a prfixed abbb. Is to be noted Reviving a fourteen year-old thread? That has to be some kind of record. -- https://mail.python.org/mailman/listinfo/python-list
trivial import question
The underscore relative to a prfixed abbb. Is to be noted -- https://mail.python.org/mailman/listinfo/python-list
Import Question
How long does it take for the program to import something? I am asking this because i have like 7 imports at the beginning of my program and i am thinking thats the reason why it is slow to start up. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Import Question
Il 20/02/2013 21:53, eli m ha scritto: How long does it take for the program to import something? I am asking this because i have like 7 imports at the beginning of my program and i am thinking thats the reason why it is slow to start up. Thanks in advance. It depend of your code module code.. if inside your module there is some code (no def or class) this code will be executed, and if for example you have some loop or some db query this will be executed too. regards, Matteo -- http://mail.python.org/mailman/listinfo/python-list
Re: Import Question
you can check each import as it varies in loading time: time python -c import [name of module] example: time python -c import flask On Wed, Feb 20, 2013 at 12:53 PM, eli m techgeek...@gmail.com wrote: How long does it take for the program to import something? I am asking this because i have like 7 imports at the beginning of my program and i am thinking thats the reason why it is slow to start up. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Import Question
On 02/20/2013 03:53 PM, eli m wrote: How long does it take for the program to import something? I am asking this because i have like 7 imports at the beginning of my program and i am thinking thats the reason why it is slow to start up. Thanks in advance. That would be easy to measure. If you just want a visible indication, put a print before and after those imports, and see how long between. Or use the time module to measure it. Notice that it's possible to write a module that consumes hours during import. All top level code will be executed. So if there's any substantial code there that's not conditional, it'll cost you. For the rest of the message, I'll assume you don't have any time-consuming initialization code. Since there are dozens of imports that happen before your code even begins, I doubt if your own imports make that much difference. Further, some of them are probably already imported, and it's very fast to import something already in the cache. About as long as a dict lookup followed by an assignment. When I look at len(list(sys.modules.iterkeys())) in Python 2.7.3, I get the value 243 Some of them are binary modules, which load pretty much instantaneously, and the others are probably precompiled, but I still expect them to swamp the 7 you're doing. BTW, if you measure it, be aware that the first time you import a module, it must be compiled, but then it saves as a .pyc file, and the next time it'll be much quicker. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
2010/2/6 Gabriel Genellina gagsl-...@yahoo.com.ar En Fri, 05 Feb 2010 13:21:47 -0300, Andrew Degtiariov andrew.degtiar...@gmail.com escribió: Code of our project has split into several packages and we deploy the project using buildout. All worked fine until I need to dynamically inspect python modules. Entirely by luck, I'd say :) ├───project.api.config │ ├───project │ │ └───api │ │ └───config │ │ └───settings │ └───project.api.config.egg-info ├───project.api.contacts │ ├───project │ │ └───api │ │ └───contacts │ │ ├───importer │ │ └───views │ └───project.api.contacts.egg-info Regular code like import project.api.config worked fine, but now I'm tryed __import__('project.api.config'): $ bin/python import project.api.config __import__('project.api.config') module 'project from 'c:\users\ad\project\src\project.api.contacts\project\__init__.pyc' If someone is interesting - __import__ works but imp doesn't. In my example: m = __import__('project.api.config') m module 'project from 'c:\users\ad\project\src\project.api.contacts\project\__init__.pyc' m.api module 'project.api from 'c:\users\ad\project\src\project.api.contacts\project\api\__init__.pyc' m.api.config module 'project.api.config' from'c:\users\ad\project\src\project.api.config\project\api\config\__init__.pyc' Please note that the m and m.api pointed to first installing package with namespace project.api but m.api.config have pointed to the proper file. And releasing code with several distributions it is one of goals of Distribute. And you might look to pypi for... zope. There is lot of package which names starts from zope. It's really convenient -- Andrew Degtiariov DA-RIPE -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
En Mon, 08 Feb 2010 06:37:53 -0300, Andrew Degtiariov andrew.degtiar...@gmail.com escribió: 2010/2/6 Gabriel Genellina gagsl-...@yahoo.com.ar En Fri, 05 Feb 2010 13:21:47 -0300, Andrew Degtiariov andrew.degtiar...@gmail.com escribió: Code of our project has split into several packages and we deploy the project using buildout. All worked fine until I need to dynamically inspect python modules. Entirely by luck, I'd say :) ├───project.api.config │ ├───project │ │ └───api │ │ └───config │ │ └───settings │ └───project.api.config.egg-info ├───project.api.contacts │ ├───project │ │ └───api │ │ └───contacts │ │ ├───importer │ │ └───views │ └───project.api.contacts.egg-info If someone is interesting - __import__ works but imp doesn't. In my example: m = __import__('project.api.config') m module 'project from 'c:\users\ad\project\src\project.api.contacts\project\__init__.pyc' m.api module 'project.api from 'c:\users\ad\project\src\project.api.contacts\project\api\__init__.pyc' m.api.config module 'project.api.config' from'c:\users\ad\project\src\project.api.config\project\api\config\__init__.pyc' Please note that the m and m.api pointed to first installing package with namespace project.api but m.api.config have pointed to the proper file. And releasing code with several distributions it is one of goals of Distribute. And you might look to pypi for... zope. There is lot of package which names starts from zope. It's really convenient Those are called namespace packages. Zope and Plone (ab)use them extensively. The intended usage is to break up a big, monolithic package [0] in parts that can be distributed independently. To implement a namespace package, you need an empty __init__.py file with only these lines [1]: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) But think carefully if you really need namespace packages; they solve a specific problem, aren't a general purpose technique. See [2] for a discussion. [0] Think of a huge behemoth with a Z O P E sign on both sides :) [1] http://docs.python.org/library/pkgutil.html [2] http://weblion.psu.edu/news/are-we-overusing-namespace-packages -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
Those are called namespace packages. Zope and Plone (ab)use them extensively. The intended usage is to break up a big, monolithic package [0] in parts that can be distributed independently. To implement a namespace package, you need an empty __init__.py file with only these lines [1]: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) But think carefully if you really need namespace packages; they solve a specific problem, aren't a general purpose technique. See [2] for a discussion. [0] Think of a huge behemoth with a Z O P E sign on both sides :) [1] http://docs.python.org/library/pkgutil.html [2] http://weblion.psu.edu/news/are-we-overusing-namespace-packages Hm.. We are using pkg_resources.declare_namespace(__name__) but I think pkgutil is much better. And we are using buildout so the omelette might help me. Link [2] very interesting. Thank you, Gabrial. -- Andrew Degtiariov DA-RIPE -- http://mail.python.org/mailman/listinfo/python-list
Import question
Code of our project has split into several packages and we deploy the project using buildout. All worked fine until I need to dynamically inspect python modules. Here is structure of our src directory ├───project.api.config │ ├───project │ │ └───api │ │ └───config │ │ └───settings │ └───project.api.config.egg-info ├───project.api.contacts │ ├───project │ │ └───api │ │ └───contacts │ │ ├───importer │ │ └───views │ └───project.api.contacts.egg-info ├───project.api.core │ ├───project │ │ └───api │ │ └───core │ │ ├───js │ │ ├───lib │ │ ├───management │ │ │ └───commands │ │ ├───middleware │ │ ├───sessions │ │ └───users │ └───project.api.core.egg-info Buildout by itself generates bin/python which look like: import sys sys.path[0:0] = [ 'c:\\users\\ad\\project\\src\\project.api.core', 'c:\\users\\ad\\project\\src\\project.api.config', 'c:\\users\\ad\\project\\src\\project.api.contacts', 'c:\\users\\ad\\project\\eggs\\lockfile-0.8-py2.6.egg', 'c:\\users\\ad\\project\\parts\\django', 'c:\\users\\ad\\project\\eggs\\web.py-0.33-py2.6.egg', Regular code like import project.api.config worked fine, but now I'm tryed __import__('project.api.config'): $ bin/python import project.api.config __import__('project.api.config') module 'project from 'c:\users\ad\project\src\project.api.contacts\project\__init__.pyc' What's wrong? Ok, I'm trying imp: import imp imp.find_module('project.api.config') Traceback (most recent call last): File console, line 1, in module ImportError: No module named project.api.config import sys sys.path[1] 'c:\\users\\ad\\project\\src\\project.api.config' imp.find_module('project.api.config', sys.path[1]) Traceback (most recent call last): File console, line 1, in module ImportError: No frozen submodule named c:\users\ad\project\src\project.api.config.project.api.config There is setup.py for project.api.config: import os from setuptools import setup, find_packages name = project.api.config install_requires = [ 'zc.buildout', 'setuptools', 'web.py=0.33', 'project.api.core', 'Django=1.1.0', 'lockfile' ] if sys.platform != 'win32': install_requires.append('python-daemon') setup( name = name, version = 1.0, author = Andrew Degtiariov, author_email = andrew.degtiar...@gmail.com, description = ..., license = Commercial, packages=find_packages(os.path.dirname(__file__), exclude=['ez_setup']), namespace_packages=['project, 'project.api'], include_package_data=True, zip_safe=False, install_requires = install_requires ) What's wrong? We really need to split the code for several eggs and want that all of our package's names starts from 'project.api' -- Andrew Degtiariov DA-RIPE -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
En Fri, 05 Feb 2010 13:21:47 -0300, Andrew Degtiariov andrew.degtiar...@gmail.com escribió: Code of our project has split into several packages and we deploy the project using buildout. All worked fine until I need to dynamically inspect python modules. Entirely by luck, I'd say :) ├───project.api.config │ ├───project │ │ └───api │ │ └───config │ │ └───settings │ └───project.api.config.egg-info ├───project.api.contacts │ ├───project │ │ └───api │ │ └───contacts │ │ ├───importer │ │ └───views │ └───project.api.contacts.egg-info Regular code like import project.api.config worked fine, but now I'm tryed __import__('project.api.config'): $ bin/python import project.api.config __import__('project.api.config') module 'project from 'c:\users\ad\project\src\project.api.contacts\project\__init__.pyc' You can't use dots neither in module names nor package names as they're identifiers [1]. It's like trying to use an attribute named 'foo.bar': you can handle it with getattr/setattr, but normal attribute access won't work: py x.foo.bar = 1 Traceback (most recent call last): File stdin, line 1, in module AttributeError: X instance has no attribute 'foo' py setattr(x, 'foo.bar', 1) py x.foo.bar Traceback (most recent call last): File stdin, line 1, in module AttributeError: X instance has no attribute 'foo' py getattr(x, 'foo.bar') 1 [1] http://docs.python.org/reference/simple_stmts.html#the-import-statement What's wrong? We really need to split the code for several eggs and want that all of our package's names starts from 'project.api' The only sane solution is to avoid using dots in package names. Sorry, but having project.api.config, project.api.contacts as directory names is simply crazy. Looks like you actually wanted to use this layout: project/ api/ config/ ... contacts/ ... core/ ... but made a wrong turn in the road... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: A package import question
En Fri, 13 Jun 2008 22:38:24 -0300, Dan Yamins [EMAIL PROTECTED] escribió: Gabriel, thanks. I understood about the fact that import only loads the first time, but didn't realize that del only removes the bound reference to the object, not as I had hoped the thing from the namespace itself. Also, I did _try_ to use reload. however, that failed since .archive was no longer an attribute associated with Operations: import Operations.archive del Operations.archive reload(Operations.archive) Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'module' object has no attribute 'archive' I don't get *why* do you want to remove the 'archive' attribute before reloading the module. Just reload it *without* using `del` previously. It seems unfortunately that the del operation on the one hand doesn't really remove the .archive from memory but just it's bound name, but nonetheless prevents me from reloading the object kept in memory. I guess I'm trying to find a clean way to remove all the attributes associated with a module when I reload it. Is there any way to do this? (The operation of recursively searching through the attributes of the module and deleting those first seems to be bad since when I did that and then try to _reload_ the module, the attributes I deleted are _not_ reloaded.) When you reload a module, new definitions for existing names replace the old objects; new names are added; old names without a new value keep the previous value. (That is, objects are *replaced* and *added* but not *removed*). Isn't it enough? Or do you actually want to be sure that old names, now unused, are no longer available? -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
A package import question
I'm having a problem importing a package in python, deleting some of what's been imported, and then reimporting. (I'm the sure the problem is trivial, but I just don't understand it.) I have a directory of python modules called Operations. It contains a python module called archive.py.Here's a import of the archive module via package import: Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type help, copyright, credits or license for more information. import Operations.archive Operations.archive module 'Operations.archive' from 'Operations/archive.pyc' So far, so good. But now, suppose I want to delete Operations.archive. then, I can't reimport it. instead, I del Operations.archive import Operations.archive dir() ['Operations', '__builtins__', '__doc__', '__name__'] Instead of getting 'Operations.archive', I just seem to get 'Operations'. I can't seem to be able to import Operations.archive without quitting the python interpreter and starting again. What's going on here, and how do I fix it? Thanks, Dan -- http://mail.python.org/mailman/listinfo/python-list
Another (perhaps similar) import question
I also have noticed another (to me) strange thing about module imports. If anyone could explain this to me, that would be great (I apologize if it's too elementary for this list.) Suppose I have a module #file: testmodule.py a = 1 When importing this module, obviously 'a' becomes an attribute of testmodule: import testmodule dir(testmodule) ['__builtins__', '__doc__', '__file__', '__name__', 'a'] Now, supposed I modify the file to: #file: testmodule.py A = 1 and then reload: reload(testmodule) module 'testmodule' from 'testmodule.py' Now, the reported attributes still include the old 'a': dir(testmodule) ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a'] Why does this happen? Moreover, even if I delete the module from memory and then reload, I _still_ get the old attribute 'a': del testmodule import testmodule dir(testmodule) ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a'] What is the principle behind this? And, is there some simple way (other than restarting the interpreter) of reloading that wipes out the old attributes associated with a given name so that spurious attributes do not remain? Thanks again (and apologies of this is a stupid question) Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Another (perhaps similar) import question
Dan Yamins wrote: I also have noticed another (to me) strange thing about module imports. If anyone could explain this to me, that would be great (I apologize if it's too elementary for this list.) Suppose I have a module #file: testmodule.py a = 1 When importing this module, obviously 'a' becomes an attribute of testmodule: import testmodule dir(testmodule) ['__builtins__', '__doc__', '__file__', '__name__', 'a'] Now, supposed I modify the file to: #file: testmodule.py A = 1 and then reload: reload(testmodule) module 'testmodule' from 'testmodule.py' Now, the reported attributes still include the old 'a': dir(testmodule) ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a'] Why does this happen? 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. Moreover, even if I delete the module from memory and then reload, I _still_ get the old attribute 'a': But in fact you did *not* delete the module from memory. A module import goes through two phases, only one of which you have access to... Phase 1. Read/parse/execute each statement, and keep the resulting namespace internally adn hidden from the user. (This is only done once.) Phase 2. Bind the module to a local name. (This may be done many times) This import xyz may or may not cause module xyz to be read/parsed/run (depending of whether it's the first time imported or not), and then it binds the resulting module namespace to the variable xyz. Your del of the module just removed the one reference to it, but that's all. del testmodule import testmodule dir(testmodule) ['A', '__builtins__', '__doc__', '__file__', '__name__', 'a'] What is the principle behind this? And, is there some simple way (other than restarting the interpreter) of reloading that wipes out the old attributes associated with a given name so that spurious attributes do not remain? No. Conclusion: Don't use reload (ever). A dozen years of Python programming, and I've never used it even once. If there is a good use case for reload, you are probably years from being there. Thanks again (and apologies of this is a stupid question) Not stupid. It will all start making sense soon. Gary Herron Dan -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: A package import question
En Fri, 13 Jun 2008 20:01:56 -0300, Dan Yamins [EMAIL PROTECTED] escribió: I'm having a problem importing a package in python, deleting some of what's been imported, and then reimporting. (I'm the sure the problem is trivial, but I just don't understand it.) I have a directory of python modules called Operations. It contains a python module called archive.py.Here's a import of the archive module via package import: Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type help, copyright, credits or license for more information. import Operations.archive Operations.archive module 'Operations.archive' from 'Operations/archive.pyc' So far, so good. Note that if you execute dir() at this point, you'll see the Operations name, *not* Operations.archive. The statement import Operations.archive first tries to locate and load a module named Operations - and *that* name is added to the current namespace, not Operations.archive (which is an invalid name by itself). But now, suppose I want to delete Operations.archive. then, I can't reimport it. instead, I del Operations.archive You have removed the archive attribute from the object to which the Operations name is referring to. import Operations.archive Python keeps a reference to all imported modules in sys.modules; if a module was already imported, any subsequent imports of the same module just return the existing reference. If you want to force Python to re-read the module from file, use the reload function. But please read the warnings at http://docs.python.org/lib/built-in-funcs.html#l2h-61 dir() ['Operations', '__builtins__', '__doc__', '__name__'] Instead of getting 'Operations.archive', I just seem to get 'Operations'. You would never get a dotted name from dir(), unless you play tricks with locals()/globals() I can't seem to be able to import Operations.archive without quitting the python interpreter and starting again. What's going on here, and how do I fix it? reload() may be what you need, but again, make sure you read the documentation before using it. reload is not a magic wand. Remember that names imported from the old module definition continue to be bound to the old objects, and all instances of classes defined in the old module continue to use the old class definitions, among other things. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Another (perhaps similar) import question
Dan Yamins wrote: What is the principle behind this? And, is there some simple way (other than restarting the interpreter) of reloading that wipes out the old attributes associated with a given name so that spurious attributes do not remain? No. Conclusion: Don't use reload (ever). A dozen years of Python programming, and I've never used it even once. If there is a good use case for reload, you are probably years from being there. Gary, thanks very much for your help.I suspected it was something like this. I still can quite tell however if the problem you describe here is the same type of issue that was behind my first problem (posted just before) with the package imports. I guess the think is, feel that I basically _have_ to have some way to reload. I'm trying to code an application that allows users to load new mathematical operations into a list of operations, and then be able to update them after trying them out on some data variables loaded into memory. If every time they change the functions in the modules to get them to produce the right results, they have to restart the interpreter, they'll always lose the data variables that they've loaded and operated on.I need to find some way that they can reload to access the modified version without having to re-do all the command-line things they've done so far. The reload command seems like the only (and natural) way to do this. Thanks, Dan Please keep responses to python-list discussion on python-list, not my personal mail box. -- Thanks. I'd suggest using modules for your system's code, and exec (or execfile) to read and parse user supplied code snippets. The result of an exec of user supplied code will be very similar to a module import, and it will be using import and exec as they were intended. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: A package import question
You have removed the archive attribute from the object to which the Operations name is referring to. import Operations.archive Python keeps a reference to all imported modules in sys.modules; if a module was already imported, any subsequent imports of the same module just return the existing reference. If you want to force Python to re-read the module from file, use the reload function. But please read the warnings at http://docs.python.org/lib/built-in-funcs.html#l2h-61 Gabriel, thanks. I understood about the fact that import only loads the first time, but didn't realize that del only removes the bound reference to the object, not as I had hoped the thing from the namespace itself. Also, I did _try_ to use reload. however, that failed since .archive was no longer an attribute associated with Operations: import Operations.archive del Operations.archive reload(Operations.archive) Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'module' object has no attribute 'archive' It seems unfortunately that the del operation on the one hand doesn't really remove the .archive from memory but just it's bound name, but nonetheless prevents me from reloading the object kept in memory. I guess I'm trying to find a clean way to remove all the attributes associated with a module when I reload it. Is there any way to do this? (The operation of recursively searching through the attributes of the module and deleting those first seems to be bad since when I did that and then try to _reload_ the module, the attributes I deleted are _not_ reloaded.) On Fri, Jun 13, 2008 at 9:09 PM, Gabriel Genellina [EMAIL PROTECTED] wrote: En Fri, 13 Jun 2008 20:01:56 -0300, Dan Yamins [EMAIL PROTECTED] escribió: I'm having a problem importing a package in python, deleting some of what's been imported, and then reimporting. (I'm the sure the problem is trivial, but I just don't understand it.) I have a directory of python modules called Operations. It contains a python module called archive.py.Here's a import of the archive module via package import: Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type help, copyright, credits or license for more information. import Operations.archive Operations.archive module 'Operations.archive' from 'Operations/archive.pyc' So far, so good. Note that if you execute dir() at this point, you'll see the Operations name, *not* Operations.archive. The statement import Operations.archive first tries to locate and load a module named Operations - and *that* name is added to the current namespace, not Operations.archive (which is an invalid name by itself). But now, suppose I want to delete Operations.archive. then, I can't reimport it. instead, I del Operations.archive You have removed the archive attribute from the object to which the Operations name is referring to. import Operations.archive Python keeps a reference to all imported modules in sys.modules; if a module was already imported, any subsequent imports of the same module just return the existing reference. If you want to force Python to re-read the module from file, use the reload function. But please read the warnings at http://docs.python.org/lib/built-in-funcs.html#l2h-61 dir() ['Operations', '__builtins__', '__doc__', '__name__'] Instead of getting 'Operations.archive', I just seem to get 'Operations'. You would never get a dotted name from dir(), unless you play tricks with locals()/globals() I can't seem to be able to import Operations.archive without quitting the python interpreter and starting again. What's going on here, and how do I fix it? reload() may be what you need, but again, make sure you read the documentation before using it. reload is not a magic wand. Remember that names imported from the old module definition continue to be bound to the old objects, and all instances of classes defined in the old module continue to use the old class definitions, among other things. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Another (perhaps similar) import question
Please keep responses to python-list discussion on python-list, not my personal mail box. -- Thanks. Sorry. When I hit reply on gmail to your message, your personal email comes up as opposed to the python list address. My apologies for not looking for closely. I'd suggest using modules for your system's code, and exec (or execfile) to read and parse user supplied code snippets. The result of an exec of user supplied code will be very similar to a module import, and it will be using import and exec as they were intended. Wow, thanks very much for introducing my to the execfile command, I've been looking for something like it. I see how this removes the issue of needing reload. Great. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Simple import question about mac osx
Hi, I have this code (learning from Core Python, Chun's book), module named chap2.py. class FooClass(object): version=0.1 def __init__(self, nm='John Doe'): self.name=nm print 'Created a class instance for ', nm def showname(self): print 'Your name is', self.name print 'My name is', self.__class__.__name__ On Windows, if I compile this and then in the python interpreter type: import chap2 foo1=FooClass() Created a class instance for John Doe If I do the same think on my Mac OS X 10.5.2 NameError: name 'FooClass' is not defined. I thought it was the path and did export PATH=$PATH:/mypath/ topythoncode but it did not help. What am I doing wrong? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Apr 29, 1:16 pm, jmDesktop [EMAIL PROTECTED] wrote: Hi, I have this code (learning from Core Python, Chun's book), module named chap2.py. class FooClass(object): version=0.1 def __init__(self, nm='John Doe'): self.name=nm print 'Created a class instance for ', nm def showname(self): print 'Your name is', self.name print 'My name is', self.__class__.__name__ On Windows, if I compile this and then in the python interpreter type: import chap2 foo1=FooClass() Created a class instance for John Doe If I do the same think on my Mac OS X 10.5.2 NameError: name 'FooClass' is not defined. I thought it was the path and did export PATH=$PATH:/mypath/ topythoncode but it did not help. What am I doing wrong? Thank you. forgot to say that on the mac I can do import chap2, but when I try and instantiate I get the error above. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Apr 29, 12:46 pm, jmDesktop [EMAIL PROTECTED] wrote: On Apr 29, 1:16 pm, jmDesktop [EMAIL PROTECTED] wrote: Hi, I have this code (learning from Core Python, Chun's book), module named chap2.py. class FooClass(object): version=0.1 def __init__(self, nm='John Doe'): self.name=nm print 'Created a class instance for ', nm def showname(self): print 'Your name is', self.name print 'My name is', self.__class__.__name__ On Windows, if I compile this and then in the python interpreter type: import chap2 foo1=FooClass() Created a class instance for John Doe If I do the same think on my Mac OS X 10.5.2 NameError: name 'FooClass' is not defined. I thought it was the path and did export PATH=$PATH:/mypath/ topythoncode but it did not help. What am I doing wrong? Thank you. forgot to say that on the mac I can do import chap2, but when I try and instantiate I get the error above. It shouldn't work under Windows, either. You have to qualify the name of the class with the name of the module, as in chap2.FooClass(). Or you can type from chap2 import FooClass and then you'll be able to simply say FooClass(). -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Apr 29, 1:54 pm, [EMAIL PROTECTED] wrote: On Apr 29, 12:46 pm, jmDesktop [EMAIL PROTECTED] wrote: On Apr 29, 1:16 pm, jmDesktop [EMAIL PROTECTED] wrote: Hi, I have this code (learning from Core Python, Chun's book), module named chap2.py. class FooClass(object): version=0.1 def __init__(self, nm='John Doe'): self.name=nm print 'Created a class instance for ', nm def showname(self): print 'Your name is', self.name print 'My name is', self.__class__.__name__ On Windows, if I compile this and then in the python interpreter type: import chap2 foo1=FooClass() Created a class instance for John Doe If I do the same think on my Mac OS X 10.5.2 NameError: name 'FooClass' is not defined. I thought it was the path and did export PATH=$PATH:/mypath/ topythoncode but it did not help. What am I doing wrong? Thank you. forgot to say that on the mac I can do import chap2, but when I try and instantiate I get the error above. It shouldn't work under Windows, either. You have to qualify the name of the class with the name of the module, as in chap2.FooClass(). Or you can type from chap2 import FooClass and then you'll be able to simply say FooClass().- Hide quoted text - - Show quoted text - Thanks. That worked on mac. But it does work like I said in Windows. Don't know why. Mr. Chun must also be using Windows because that is the way he does it in his book. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Tue, Apr 29, 2008 at 2:14 PM, jmDesktop [EMAIL PROTECTED] wrote: Thanks. That worked on mac. But it does work like I said in Windows. Don't know why. Mr. Chun must also be using Windows because that is the way he does it in his book. It shouldn't work that way on windows either. Can you tell us a little more about what you mean when you say you compile this under windows? Normally, python code doesn't need to be compiled, so I'm wondering if you're doing something different from what we expect when you say you compile it and then import it in the interpreter. Are you by any chance writing code in IDLE, running it, then doing things in the interpreter? -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Apr 29, 2:37 pm, Jerry Hill [EMAIL PROTECTED] wrote: On Tue, Apr 29, 2008 at 2:14 PM, jmDesktop [EMAIL PROTECTED] wrote: Thanks. That worked on mac. But it does work like I said in Windows. Don't know why. Mr. Chun must also be using Windows because that is the way he does it in his book. It shouldn't work that way on windows either. Can you tell us a little more about what you mean when you say you compile this under windows? Normally, python code doesn't need to be compiled, so I'm wondering if you're doing something different from what we expect when you say you compile it and then import it in the interpreter. Are you by any chance writing code in IDLE, running it, then doing things in the interpreter? -- Jerry On Windows I took the text file I created on mac with vi and opened it in PythonWin. I ran it. It compiled. I run the import and call from the python interpreter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Apr 29, 2:17 pm, jmDesktop [EMAIL PROTECTED] wrote: On Apr 29, 2:37 pm, Jerry Hill [EMAIL PROTECTED] wrote: On Tue, Apr 29, 2008 at 2:14 PM, jmDesktop [EMAIL PROTECTED] wrote: Thanks. That worked on mac. But it does work like I said in Windows. Don't know why. Mr. Chun must also be using Windows because that is the way he does it in his book. It shouldn't work that way on windows either. Can you tell us a little more about what you mean when you say you compile this under windows? Normally, python code doesn't need to be compiled, so I'm wondering if you're doing something different from what we expect when you say you compile it and then import it in the interpreter. Are you by any chance writing code in IDLE, running it, then doing things in the interpreter? -- Jerry On Windows I took the text file I created on mac with vi and opened it in PythonWin. I ran it. It compiled. I run the import and call from the python interpreter. Well, Python compiles automatically any .py file that you import. Of course this isn't machine code like the one from a C compiled executable. It's Python's own bytecode. But normally you shouldn't worry about that bytecode; actually, you shouldn't even be paying attention to it. All that concerns you is that you created a module and that you can import it. Leave the whole compiling concept to the interpreter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Tue, Apr 29, 2008 at 3:17 PM, jmDesktop [EMAIL PROTECTED] wrote: On Windows I took the text file I created on mac with vi and opened it in PythonWin. I ran it. It compiled. I run the import and call from the python interpreter. You're not doing what you think you're doing. I'm not sure I know the right way to explain it, though. When you run your code in pythonwin, it's just like calling 'python -i chap2.py' It runs the code in chap2.py, then gives you an interpreter window to interact with your code. In this case, that means that FooClass is visible with no import at all, because it was defined in the scope of the currently running script, as opposed to being imported. You haven't said exactly how you're doing this on your mac, but I'm guessing that you're opening a command line, starting up the python interpreter, then going from there? Can someone help me out? I'm running into a mental block on how to explain the difference between doing this: C:\Python25python -i chap2.py foo1=FooClass() Created a class instance for John Doe and doing this: C:\Python25python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import chap2 foo1=chap2.FooClass() Created a class instance for John Doe -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple import question about mac osx
On Apr 29, 3:47 pm, Jerry Hill [EMAIL PROTECTED] wrote: When you run your code in pythonwin, it's just like calling 'python -i chap2.py' It runs the code in chap2.py, then gives you an interpreter window to interact with your code. In this case, that means that FooClass is visible with no import at all, because it was defined in the scope of the currently running script, as opposed to being imported. You haven't said exactly how you're doing this on your mac, but I'm guessing that you're opening a command line, starting up the python interpreter, then going from there? Can someone help me out? I'm running into a mental block on how to explain the difference between doing this: C:\Python25python -i chap2.py foo1=FooClass() jmDesktop, With what Jerry stated, You can see what is happening under PythonWin interactive window by doing: dir() before and after running chap2.py and see that FooClass is defined without import, which gives a clue that PythonWin is not running the script independant of the interactive window. Or try adding the following to the end of your chap2.py: print Hello World somevar = 12345 And run in PythonWin and see what happens to your interactive window and if somevar is defined. If you close and open PythonWin and use the interactive window without having first run chap2.py, you will find it behaves the same as the mac. Ivan -- http://mail.python.org/mailman/listinfo/python-list
Library package import question
Hello, I have a python library package 'Foo', which contains alot of submodules: Foo/: __init__.py module1.py: class Bar() class Hmm() module2.py class Bee() class Wax() module3.py etc etc To prevent namespace pollution, I want to import and use this library in the following way: import Foo (...) t = Foo.module2.Bee() To accomplish this, I put explicit imports in __init__.py: import module1 import module2 import module3 what Im wondering about, is if its a more refined way of doing this, as the explicit imports now need to be manually maintained if the library grows. I've tried to use __all__, but this only seems to work with from Foo import * and it causes modules to be imported directly into the namespace of course. Thanks for input. -Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: Library package import question
2007/11/5, Frank Aune [EMAIL PROTECTED]: To prevent namespace pollution, I want to import and use this library in the following way: import Foo (...) t = Foo.module2.Bee() from x import y as z that has always worked for me to prevent pollution... -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours -- http://mail.python.org/mailman/listinfo/python-list
Re: Library package import question
En Mon, 05 Nov 2007 10:34:26 -0300, Frank Aune [EMAIL PROTECTED] escribió: I have a python library package 'Foo', which contains alot of submodules: Foo/: __init__.py module1.py: class Bar() class Hmm() module2.py class Bee() class Wax() module3.py etc etc To prevent namespace pollution, I want to import and use this library in the following way: import Foo (...) t = Foo.module2.Bee() To accomplish this, I put explicit imports in __init__.py: import module1 import module2 import module3 what Im wondering about, is if its a more refined way of doing this, as the explicit imports now need to be manually maintained if the library grows. I've tried to use __all__, but this only seems to work with from Foo import * and it causes modules to be imported directly into the namespace of course. If I understand your question right, you want some way to automatically enumerate and import all *.py files inside your package. Try this inside Foo/__init__.py: code def import_all_modules(): Import all modules in this directory import os.path pkgdir = os.path.dirname(__file__) for filename in os.listdir(pkgdir): modname, ext = os.path.splitext(filename) if ext=='.py' and modname!='__init__': __import__(modname, globals()) import_all_modules() del import_all_modules /code -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
package import question
Hi all, I have the following directory structure: wallpaper/ -main.py -ng/ -- __init__.py -- setdesktop.py -yb/ -- __init__.py -- setdesktop.py From main.py, I would like to do: import ng import yb ng.setdesktop.run() yb.setdesktop.run() But it is not working! when I import the package, the modules present inside the package are getting imported. However, following the python document if I do import ng.setdesktop import yb.setdesktop ng.setdesktop.run() yb.setdesktop.run() Works fine. I would like to use the notation. import my_package_name and use the modules inside the package in the dotted module notation. What should I do the enable such a kind of imports. Please let me know. Thank you. Senthil -- http://mail.python.org/mailman/listinfo/python-list
Re: package import question
Phoe6 wrote: Hi all, I have the following directory structure: wallpaper/ -main.py -ng/ -- __init__.py -- setdesktop.py -yb/ -- __init__.py -- setdesktop.py From main.py, I would like to do: import ng import yb ng.setdesktop.run() yb.setdesktop.run() But it is not working! when I import the package, the modules present inside the package are getting imported. However, following the python document if I do import ng.setdesktop import yb.setdesktop ng.setdesktop.run() yb.setdesktop.run() Works fine. I would like to use the notation. import my_package_name and use the modules inside the package in the dotted module notation. What should I do the enable such a kind of imports. Please let me know. You need to import the setdesktop-module in the respective __init__.py-files to make them part of the names known in there. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: package import question
Phoe6 wrote: Hi all, I have the following directory structure: wallpaper/ -main.py -ng/ -- __init__.py -- setdesktop.py -yb/ -- __init__.py -- setdesktop.py From main.py, I would like to do: import ng import yb ng.setdesktop.run() yb.setdesktop.run() But it is not working! when I import the package, the modules present inside the package are getting imported. However, following the python document if I do import ng.setdesktop import yb.setdesktop ng.setdesktop.run() yb.setdesktop.run() Works fine. I would like to use the notation. import my_package_name and use the modules inside the package in the dotted module notation. What should I do the enable such a kind of imports. Put the line from . import setdesktop into both __init__.py files. Importing the package will then trigger the submodule to be imported. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: package import question
On Oct 22, 1:24 pm, Peter Otten [EMAIL PROTECTED] wrote: Phoe6 wrote: Hi all, I have the following directory structure: wallpaper/ -main.py -ng/ -- __init__.py -- setdesktop.py -yb/ -- __init__.py -- setdesktop.py From main.py, I would like to do: import ng import yb ng.setdesktop.run() yb.setdesktop.run() But it is not working! when I import the package, the modules present inside the package are getting imported. However, following the python document if I do import ng.setdesktop import yb.setdesktop ng.setdesktop.run() yb.setdesktop.run() Works fine. I would like to use the notation. import my_package_name and use the modules inside the package in the dotted module notation. What should I do the enable such a kind of imports. Put the line from . import setdesktop into both __init__.py files. Importing the package will then trigger the submodule to be imported. Thanks a lot for your replies. I had a thought that I can do this way, but as Python Documentation did not mention it, I was 'thinking' that submodules will automatically get imported and __init__.py usually blank. Thanks again, Senthil -- http://mail.python.org/mailman/listinfo/python-list
Import question
can I import more then one modules like this: import module,module2 ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
Lamonte Harris wrote: can I import more then one modules like this: import module,module2 So your'e basically saying that you haven't tried it? /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
Lamonte Harris wrote: On 8/22/07, *Wildemar Wildenburger* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: So your'e basically saying that you haven't tried it? No I haven't. Thats why I asked? Common sense? Sorry. Excuse my sarcasm. The common way for answering easy questions like this one is firing up the interpreter and trying it for yourself. You don't go up to a shoestore clerk to ask whether your shoes might fall off if you tie them sloppily, do you? Thats just wasting everyones time. And regarding your question: Python 2.5 (r25:51908, Apr 10 2007, 10:29:13) [GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] on linux2 Type help, copyright, credits or license for more information. import sys, datetime sys.platform, datetime.datetime.now() ('linux2', datetime.datetime(2007, 8, 23, 0, 1, 41, 727155)) Hint for the future: Please try these things before asking. If *then* you have a problem, ask. /W -- http://mail.python.org/mailman/listinfo/python-list
relative import question: packaging scripts
What is the recommended packaging of demo scripts or test scripts for a package that has modules that use relative imports? Example: Suppose I have the package structure: package/ __init__.py subpackage1/ __init__.py moduleY.py subpackage2/ __init__.py moduleZ.py Important detail: moduleZ uses a relative import to access moduleY. The problem: I have a script test.py that I want to distribute with the package. It will import moduleZ to illustrate or test the module's use. Is it the case that this script cannot reasonably be bundled with `package`? (I.e., within its directory structure.) I cannot put it in the `subpackage2` directory and just import moduleZ, because then I will get ValueError: Attempted relative import in non-package I cannot put it in the `package` directory and import subpackage2.moduleZ, because then I will get ValueError: Attempted relative import beyond toplevel package The script could use path manipulation to find `package`, as suggested by Alex Martelli http://mail.python.org/pipermail/python-list/2007-May/438250.html and others. However it has also been claimed that this approach is an insane for any shared code. Is it? I do not want to assume the package will be installed: a user should be able to play with it without installing it. In this case, does the only sane thing to become to require any user to take the step of inserting the package location into sys.path and have test.py rely on the user having done this? Thank you, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Organizing code - import question
On 5/3/07, Brian Blais [EMAIL PROTECTED] wrote: Carlos Hanson wrote: It looks like you need __init__.py in MyPackage. Then you can import starting with MyPackage. For example, you might use one of the following: import MyPackage from MyPackage.Common import * etc that means that MyPackage must be in the sys path too? It doesn't seem like a contained-module sees the container in any way. That is exactly right. Without being in the sys path, Python does not know where to look to resolve the import statements. -- Carlos Hanson -- http://mail.python.org/mailman/listinfo/python-list
Organizing code - import question
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 MyClass1b.py # depends on MyClass1 Part2/ # wants to use functions in Common/ __init__.py # does from MyClass2 import MyClass2, etc,... MyClass2.py # depends on MyClass1 also, such as containing a list of MyClass1 MyClass2a.py # depends on MyClass2 MyClass2b.py # depends on MyClass2 Common/ __init__.py # does import fun1,fun2, etc,... fun1.py fun2.py So I have some common utilities that both classes want to access, and I have two separate class definitions, of which one depends on the other. In MyClass2.py, I can't seem to do: import Common.fun1 or from Part1.MyClass1 import MyClass1 I think I am either missing some syntax/path thing, or I am thinking about the organization in entirely the wrong way. Currently, as a hack, I am simply copying the code from Common into the other two directories, and making a link to the Part1 directory in the Part2 so I can import it. There must be a better way, yes? thanks, Brian Blais -- - [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
Re: Organizing code - import question
On May 3, 8:41 am, Brian Blais [EMAIL PROTECTED] wrote: 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 MyClass1b.py # depends on MyClass1 Part2/ # wants to use functions in Common/ __init__.py # does from MyClass2 import MyClass2, etc,... MyClass2.py # depends on MyClass1 also, such as containing a list of MyClass1 MyClass2a.py # depends on MyClass2 MyClass2b.py # depends on MyClass2 Common/ __init__.py # does import fun1,fun2, etc,... fun1.py fun2.py So I have some common utilities that both classes want to access, and I have two separate class definitions, of which one depends on the other. In MyClass2.py, I can't seem to do: import Common.fun1 or from Part1.MyClass1 import MyClass1 I think I am either missing some syntax/path thing, or I am thinking about the organization in entirely the wrong way. Currently, as a hack, I am simply copying the code from Common into the other two directories, and making a link to the Part1 directory in the Part2 so I can import it. There must be a better way, yes? thanks, Brian Blais -- - [EMAIL PROTECTED] http://web.bryant.edu/~bblais It looks like you need __init__.py in MyPackage. Then you can import starting with MyPackage. For example, you might use one of the following: import MyPackage from MyPackage.Common import * etc -- Carlos Hanson -- http://mail.python.org/mailman/listinfo/python-list
Re: Organizing code - import question
Carlos Hanson wrote: It looks like you need __init__.py in MyPackage. Then you can import starting with MyPackage. For example, you might use one of the following: import MyPackage from MyPackage.Common import * etc that means that MyPackage must be in the sys path too? It doesn't seem like a contained-module sees the container in any way. bb -- - [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
Re: Organizing code - import question
En Thu, 03 May 2007 12:41:00 -0300, Brian Blais [EMAIL PROTECTED] escribió: 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 MyClass1b.py # depends on MyClass1 Part2/ # wants to use functions in Common/ __init__.py # does from MyClass2 import MyClass2, etc,... MyClass2.py # depends on MyClass1 also, such as containing a list of MyClass1 MyClass2a.py # depends on MyClass2 MyClass2b.py # depends on MyClass2 Common/ __init__.py # does import fun1,fun2, etc,... fun1.py fun2.py So I have some common utilities that both classes want to access, and I have two separate class definitions, of which one depends on the other. In MyClass2.py, I can't seem to do: import Common.fun1 or from Part1.MyClass1 import MyClass1 To be able to do that, MyPackage should be on sys.path If its *container* (i.e. the directory containing MyPackage, perhaps site-packages) is already on sys.path, you could prefix all imports with the package name: import MyPackage.Common.fun1, or from MyPackage.Part1 import MyClass1 (Dont forget the __init__.py on MyPackage, to make it a real package) If you are using Python 2.5, you can use relative imports. Read the What's new document. In MyClass2.py you could use, then: from ..Common import fun1, or: from ..Part1.MyClass1 import MyClass1 -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
import question on wx ?
I have installed wx and everything looks fine. I have written a small app that uses wx. When I run my program from the console like ubuntu $ python PROGRAM_NAME.py it gives error Traceback (most recent call last): File Project.py, line 6, in ? import wx ImportError: No module named wx But if I run the program from SPE (Stani's Python Editor) it just runs fine. How can I resolve such an issue. Please help. Is my path settting worng ..? Every help is appreciated. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: import question on wx ?
[EMAIL PROTECTED] wrote: I have installed wx and everything looks fine. I have written a small app that uses wx. When I run my program from the console like ubuntu $ python PROGRAM_NAME.py it gives error Traceback (most recent call last): File Project.py, line 6, in ? import wx ImportError: No module named wx But if I run the program from SPE (Stani's Python Editor) it just runs fine. It could be that the Python version you are using to launch the app from the console is the preinstalled version on your system and therefore wxPython wasn't installed into that version. Do you have multiple versions of Python installed? Probably SPE is using the other version which *does* have wxPython in it. -- http://mail.python.org/mailman/listinfo/python-list
Re: import question on wx ?
I think what you say makes perfect sense I am using 2.4.2 python (I typed pthon -V on console to get) How can I find what my SPE editor is using ? John Salerno wrote: [EMAIL PROTECTED] wrote: I have installed wx and everything looks fine. I have written a small app that uses wx. When I run my program from the console like ubuntu $ python PROGRAM_NAME.py it gives error Traceback (most recent call last): File Project.py, line 6, in ? import wx ImportError: No module named wx But if I run the program from SPE (Stani's Python Editor) it just runs fine. It could be that the Python version you are using to launch the app from the console is the preinstalled version on your system and therefore wxPython wasn't installed into that version. Do you have multiple versions of Python installed? Probably SPE is using the other version which *does* have wxPython in it. -- http://mail.python.org/mailman/listinfo/python-list
Re: import question on wx ?
John Salerno wrote: [EMAIL PROTECTED] wrote: I have installed wx and everything looks fine. I have written a small app that uses wx. When I run my program from the console like ubuntu $ python PROGRAM_NAME.py it gives error Traceback (most recent call last): File Project.py, line 6, in ? import wx ImportError: No module named wx But if I run the program from SPE (Stani's Python Editor) it just runs fine. It could be that the Python version you are using to launch the app from the console is the preinstalled version on your system and therefore wxPython wasn't installed into that version. Do you have multiple versions of Python installed? Probably SPE is using the other version which *does* have wxPython in it. To see which versions SPE uses, go to HelpAbout and the versions are mentioned under Program info. Compare that to the version which appears if you just type python in the command prompt. I've posted a howto on the ubuntuforums how to install the latest wxpython and SPE on Ubuntu: http://www.ubuntuforums.org/showthread.php?t=218001highlight=wxpython Stani -- http://mail.python.org/mailman/listinfo/python-list
Re: import question on wx ?
That right..on my console it shows python 2.4.2 and on SPE it shows 2.4.3. The wxPython is working fine in SPE i.e with Python 2.4.3. How can I make sure that when I type python on console I get the 2.4.3 ? Every help is greatly appreciated. Thanks John Salerno wrote: [EMAIL PROTECTED] wrote: I have installed wx and everything looks fine. I have written a small app that uses wx. When I run my program from the console like ubuntu $ python PROGRAM_NAME.py it gives error Traceback (most recent call last): File Project.py, line 6, in ? import wx ImportError: No module named wx But if I run the program from SPE (Stani's Python Editor) it just runs fine. It could be that the Python version you are using to launch the app from the console is the preinstalled version on your system and therefore wxPython wasn't installed into that version. Do you have multiple versions of Python installed? Probably SPE is using the other version which *does* have wxPython in it. -- http://mail.python.org/mailman/listinfo/python-list
Re: import question on wx ?
wrote in news:[EMAIL PROTECTED] in comp.lang.python: I think what you say makes perfect sense I am using 2.4.2 python (I typed pthon -V on console to get) How can I find what my SPE editor is using ? Wherever you can run python you can find the version by running the following bit of python import sys print sys.version For example I currently get: running: python ...\test-1.py 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] from my homebrew (wxPython) editor. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
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? Handy for a lazy programmer, maybe. Confusing for the reader, though (do you mean Queue module, or Queue class? I must scroll up...). And highly tacky. I recommend avoiding it. For modules, I recommend act of words (words ending in -ing and -ion) because such words aren't common identitiers. So queuing instead of Queue. Unfortunately, the Python library isn't setting a good example here. Too much glob.glob, time.time, socket.socket, and Queue.Queue. I hope all these go away in Python 3000. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
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 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
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 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
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
Re: noob import question
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
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/ -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
PA [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
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 '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] noob import question
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 '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
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 '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: noob import question
[Please don't top-post. Please don't indiscriminately quote the entire message you respond to. URL:http://en.wikipedia.org/wiki/Top_posting] Brian Blazer [EMAIL PROTECTED] writes: Thank you for your responses. I had a feeling is had something to do with a namespace issue but I wasn't sure. Another point to note is that 'from foo import *' is bad practice. It causes a problem known as namespace pollution, where you can't tell where a particular name you're using comes from, or if you have accidentally clobbered an existing name. Either import the module to a single name, so you can qualify the names inside that module: import foo import awkward_long_module_name as bar foo.eggs() bar.beans() Or, if you only need a few objects from the module, import those specifically and use their names directly: from foo import spam, eggs eggs() spam() 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? Since we don't need to have one file per class, the convention is to group your modules by coherent functionality. Place any names, functions, classes, whatever that all relate to a discrete, coherent set of functionality in a single module. The Python coding guidelines[0] also recommend that the module be named all in lower-case, but that's more about consistency within your own code base. [0]: URL:http://www.python.org/dev/peps/pep-0008 -- \ I have a map of the United States; it's actual size. It says | `\ '1 mile equals 1 mile'... Last summer, I folded it. -- Steven | _o__) Wright | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly import question (__file__ attribute)
On Thu, 09 Mar 2006 17:25:20 -0500, Jack Diederich wrote: It is a built-in module so it doesn't have a .so (dll) or .py file to mention. Wouldn't it make sense for module.__file__ to be set to None rather than completely missing in this case? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly import question (__file__ attribute)
On Thu, Mar 09, 2006 at 02:04:45PM -0800, mh wrote: 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: import thread thread.__file__ Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'module' object has no attribute '__file__' A few questions. Why? Where is thread.py or thread.so? (I can't find it). Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type help, copyright, credits or license for more information. import sys import thread sys.modules['thread'] module 'thread' (built-in) thread module 'thread' (built-in) ^D sprat:~# cd ~/src/python-head/Modules/ sprat:~/src/python-head/Modules# ls thread* threadmodule.c threadmodule.o It is a built-in module so it doesn't have a .so (dll) or .py file to mention. -Jack -- http://mail.python.org/mailman/listinfo/python-list
Re: Silly import question (__file__ attribute)
mh wrote: 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: import thread thread.__file__ Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'module' object has no attribute '__file__' A few questions. Why? Where is thread.py or thread.so? (I can't find it). import sys thread in sys.builtin_module_names True /F -- http://mail.python.org/mailman/listinfo/python-list
Tricky import question.
importedfiles = {} for f in FileList f2 = f.split('.')[0] # strip the .py, .pyc __import__(f2) s2 = f2+'.main()' # main is the top file in each import c = compile(s2, '', 'eval') importedfiles[f2] = eval(c) 'importedfiles' should hold an object reference to the main() function within each imported file. The problem is, the import function works but I can't get the object reference into the imortedfiles dictionary object. the code keeps telling me NameError: name 'C1_Dosing' is not defined. in this instance C1_Dosing is the first file name in the filelist. The import worked, why not the compile ?? TIA. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky import question.
David Poundall wrote: importedfiles = {} for f in FileList f2 = f.split('.')[0] # strip the .py, .pyc __import__(f2) s2 = f2+'.main()' # main is the top file in each import c = compile(s2, '', 'eval') importedfiles[f2] = eval(c) 'importedfiles' should hold an object reference to the main() function within each imported file. The problem is, the import function works but I can't get the object reference into the imortedfiles dictionary object. the code keeps telling me NameError: name 'C1_Dosing' is not defined. in this instance C1_Dosing is the first file name in the filelist. The import worked, why not the compile ?? because your __import__ statement didn't assign the returned module to anything, so there's no C1_Dosing in the current namespace. assuming that the main function in each module returns something that you want to store in the importedfiles dictionary, here's a better way to do it: m = __import__(f2) importedfiles[f2] = getattr(m, main)() tweak as necessary. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky import question.
Sadly I get this reply when I try that. AttributeError: 'module' object has no attribute 'main' I am getting the impression that the value returned from the __import__() function is only a string reference NOT an object. I am going to have a go at trying this with the imp' module as that specifically mentions that an object is returned. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky import question.
This worked ... def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod for reasons given here... http://www.python.org/doc/2.3.5/lib/built-in-funcs.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky import question.
On 25 Oct 2005 06:39:15 -0700, David Poundall [EMAIL PROTECTED] wrote: importedfiles = {} for f in FileList f2 = f.split('.')[0] # strip the .py, .pyc importedfiles[f2] = __import__(f2).main # it sounds like all you want is the above (untested ;-), or # use __import__(f2).main() if you actually want the _result_ returned by main Either way, you don't need the following __import__(f2) s2 = f2+'.main()' # main is the top file in each import c = compile(s2, '', 'eval') importedfiles[f2] = eval(c) 'importedfiles' should hold an object reference to the main() function within each imported file. Do you want a reference to the function, or the result of calling the function? If you want a reference to the function itself, you should leave off the () after main, otherwise you will execute the function. The problem is, the import function works but I can't get the object reference into the imortedfiles dictionary object. the code keeps telling me NameError: name 'C1_Dosing' is not defined. probably your first file is C1_Dosing.py (or some other extension after the '.') so f2 becomes 'C1_Dosing' and s2 becomes 'C1_Dosing.main()' and you compile that into code bound to c, and when you try to eval(c), it tries to find C1_Dosing in the current environment, et voila! you have the error. When confronted with mysteries such as presented by your code results, I suggest you intruduce print statements to verify what you are assuming about what it is doing. E.g., you could print repr(f2) after assignment, and after the __import__ if you thought it was going to do something to f2 in the local name space, and repr(s2) after the assignment, etc. to see if I guessed right. Or a quick line to clone for a snapshot of local varibles at different points might be (untested) print '\n'.join('%15s: %s'%(k, repr(v)[:60]) for k,v in sorted(locals().items())) in this instance C1_Dosing is the first file name in the filelist. The import worked, why not the compile ?? I think the compile did work. But your code didn't produce a binding for the name 'C1_Dosing' which the code c was looking for when eval(c) was called. If you wanted to make your code work, perhaps replacing (untested) __import__(f2) with exec '%s = __import__(f2)'%f2 # bind imported module to name specified by f2 string might have got by the error in eval (c), but I suspect you would want to leave the () off the .main in any case. And why go through all that rigamarole? TIA. Try it both ways and report back what you found out ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky import question.
On 25 Oct 2005 08:51:08 -0700, David Poundall [EMAIL PROTECTED] wrote: This worked ... def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod for reasons given here... http://www.python.org/doc/2.3.5/lib/built-in-funcs.html Aha. You didn't mention multi-dot names ;-) But was that the real problem? Your original code wasn't using anything corresponding to mod above. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky import question.
All I was trying to do with my feeble code attempt, was to return a reference to the imported module so that I could do... result = instanceref.main() where main was a function within the import. Having glanced at the code in the import section of the help files all morning, when I actually sat down and read it it turned out the example code was what I needed. Its always the way. Many thanks for taking time out to reply Bengt. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tricky import question.
repr() is a new one on me I am afraid, and I have yet to achieve any decent competance with global and local lists. As you probaly noticed earlier, I managed to bungle my way through this time. However, I will log this thread away for when I next get stuck with a bindings. Thank you Bengt :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
Circular import issues can usually be resolved by moving import statements into the bodies of functions which aren't executed when the module itself is imported. Simple example: fileA.py -- import fileB as fb foo = 10# we're going to access foo from fileB fb.do_something_with_foo() fileB.py -- def do_something_with_foo(): import fileA as fa # import is INSIDE the function print foo is , fa.foo -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
ncf wrote: In file A, I have an instance of a class and then I import file B (import fileB as fb). In file B, I need to access file A's class instance. Is there anyway I can do this? (I hope that was descriptive enough :\) Let's see... # -- fileA.py class Test(object): pass myInstance = Test() import fileB as fb fb.myInstance = myInstance fb.test() # -- fileB.py myInstance = None def test(): print myInstance is %s % myInstance if __name__ == __main__: test() # -- now to the command line to test: [EMAIL PROTECTED]:~/projects/dabo/dabo/ui/uiwx $ python fileB.py myInstance is None [EMAIL PROTECTED]:~/projects/dabo/dabo/ui/uiwx $ python fileA.py myInstance is __main__.Test object at 0xb7dfcf6c Is this what you want? BTW, what you call files, we refer to as scripts (if run) or modules (if imported). -- Paul McNett http://paulmcnett.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
Hmm...thanks for the replies. Judging by this, it looks like I might still be in a slight perdiciment with doing it all, but time will tell. I wish there were a way I could reference across multiple modules. Well, thanks for your help. Hopefully I'll be able to work out some *simple* solution for all of this. -Wes -- http://mail.python.org/mailman/listinfo/python-list
Re: Import question
Crap. Forgot to mention that in some instances, I do want the class definitions to create new instances and such. Sorry :) -- http://mail.python.org/mailman/listinfo/python-list
module/import question
I'm trying to import Logilab's constraint module like this: from logilab.constraint import * from within a Python interactive session. The module is not installed correctly on our system, and it won't be, so i adjusted my PYTHONPATH, added an empty __init__.py file, then started up an interactive session. When i do the above import i get: Traceback (most recent call last): File stdin, line 1, in ? File /afs/big/long/freakin/path/to/dl/__init__.py,line 23,in ? ImportError: No module named constraint.propagation the first time i do it, then the 2nd time it succeeds w/o a complaint. The adjustment to my PYTHONPATH var was to append : afs/big/long/freakin/path/to/dl to the previous value. Any idea what i'm doing wrong? thanks in advance, E -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: module structure and import question
Thx Rob. yes i know it's related to search path, but i don't know how to set it in a practical way (beside hard coding). my concern is, if i want to create a custom module/library, i don't know what py file will import it and where the working directory should be. sometime like my example, even i don't know where the root directory of my module will place, and i expect it can place in anywhere, how should i set the sys.path? i know that maybe a stupid question, please forgive me, i'm just a newbie. i have read all online documents in python.org. but i wouldn't find the answer. yes, i'm asking is it normally only put one class in one py file. thanks for your advice. But if i put a set of classes in a py file as a module, will it increase the dependency of each class? back to my example, of course, i can put BaseA and ClassA together in one py file. what should i do when i need to add one more class later, ClassB, which also extend BaseA. Put it into the same file or in a new file? if put in in the same file, i think it should difficult to maintain versioning. i'm quite confuse in this, maybe because i learn Java before. Thx again, Rob. Rob Emmons [EMAIL PROTECTED] ??? news:[EMAIL PROTECTED] ???... hi all, i have question on how to design a module structure. for example, i have 3 files. [somewhere]/main.py [somewhere]/myLib/Base/BaseA.py [somewhere]/myLib/ClassA.py . It's fine when i run main.py. however when i run ClassA.py individually, it would fail in import statment since the import path is incorrect. I would like to know is something wrong in my design, or something i missed. I think your issue is your module search path. Take a look at the doc for sys.path in the library reference. These are the directories that python searchies for modules. Usually the . directory is included in this which makes python search the current working directory. Your example fails because your working directories are probably different when you ran the two modules. In any case always consider how you've setup sys.path and your libraries and modules. Also, in practical usage, is that one class in one py file? I'm not exactly clear what your asking -- but I think yor asking if you'd normally only put one class in one py file. My answer is no -- generally you'd put many functions and classes in each py file. Modules are high level and should be used to create libraries essentailly -- this means many fucntions and classes per module. Rob -- http://mail.python.org/mailman/listinfo/python-list
Newbie: module structure and import question
hi all, i have question on how to design a module structure. for example, i have 3 files. [somewhere]/main.py [somewhere]/myLib/Base/BaseA.py [somewhere]/myLib/ClassA.py main.py === from myLib.ClassA import ClassA a = classA() dir(a) myLib/ClassA.py === from myLib.Base.BaseA import BaseA class ClassA(BaseA): def __init__(self): BaseA.__init__(self) print classA if (__name__ == __main__): print test class A a = ClassA() print a myLib/Base/BaseA.py === class BaseA: def __init__(self): print BaseA It's fine when i run main.py. however when i run ClassA.py individually, it would fail in import statment since the import path is incorrect. I would like to know is something wrong in my design, or something i missed. Also, in practical usage, is that one class in one py file? thx! a python newbie -- http://mail.python.org/mailman/listinfo/python-list