Python Imports, Paths, Directories Modules

2024/11/13 2:35:15

Let me start by saying I've done extensive research over the course of the past week and have not yet found actual answers to these questions - just some fuzzy answers that don't really explain what is going on. If that's just cause I missed what I was looking for, I'm sorry - please just point me in the correct direction.

My directory structure is:

TestProject/runtest*testpackage/__init__.pytestmod.pytestmod2.pytestsubs/testsubmod.py

A couple notes:

  • I'm using python2.7 on Ubuntu
  • I'm testing with bpython
  • I'm running bpython from specific directories to test the way import behaves
  • I'm attempting to follow best practices.
  • This package is not installed, it's in a random dev directory
  • This directory is not in the pythonpath
  • I have a single init.py in the package directory
  • There are no init.py files in the nested directories
  • The init.py file is empty
  • testpackage/testmod.py contains TestModClass
  • testpackage/testsubs/testsubmod.py contains TestSubModClass

Things I've observed:

  • When I run bpython from TestProject/ import testpackage works
    • This does not import testpackage.testmod
    • I cannot access testpackage.testmod at all
  • When I run bpython from TestProject/ import testpackage.testmod fails
  • When I run bpython from TestProject/ from testpackage import testmod works
  • I can add code to init.py to explicitly import testmod.py, but not testsubs/testmod.py
    • I don't think this is the correct way to do this, what if the user doesn't want to import that module?
  • from testmod.py i can import testmod2, but not testpackage.testmod2
    • This would be nice to do so that I can name my own modules with overlapping names with STL or twisted (such as testpackage.logging) without causing errors (it sucks to have to name my own modules crap like customerlogging, instead of just mypackage.logging)

And the questions:

  1. Does python deal differently with imports on packages & modules that exist in the pythonpath than when you are trying to import from your current directory?
  2. Why doesn't import testpackage give me access to testpackage.testmod? When I import os, I can then access os.path (etc).
  3. With a package, should I stick to using a single init.py in the base directory, or should I be nesting them in subsequent directories?
  4. How can I import a module specifying the package name? I.E. from testmod.py, I would like to import testpackage.testmod2 rather than just testmod2.
  5. What is the proper way to import submodules from the subsubs directory?
    1. The only solution I see is to append that directory to the pythonpath from init.py, but I don't know if that's the correct way.

Thanks in advance.

Answer

First off, you will find all the information you need in section 6 of The Python Tutorial.


(1) Does python deal differently with imports on packages & modules that exist in the pythonpath than when you are trying to import from your current directory?

No, it doesn't. Actually, Python always searches sys.path when importing modules. Modules in the current directory are only found since sys.path contains an entry with the empty string, meaning the current directory.


(2) Why doesn't import testpackage give me access to testpackage.testmod? When I import os, I can then access os.path (etc).

For efficiency, import testpackage only loads testpackage/__init__.py. If you need testpackage.testmod, you have to explicitely import it:

import testpackage   # Just imports testpackage, not testpackage.testmod!
import testpackage.testmod   # Import *both* testpackage and testpackage.testmod!

If you always want to export testmod, import it within __init__.py, this is what os (os/__init__.py) does. This way, testpackage.testmod is always available implicitely if you import testpackage.

Since Python is cross-platform, there is actually no way to consistently and automatically load modules in a directory, because some filesystems are case-insensitive (Windows!). Python would not know whether to load os/path.py as os.path or os.Path, etc.


(3) With a package, should I stick to using a single __init__.py in the base directory, or should I be nesting them in subsequent directories?

You always need an __init__.py for each subpackage. There were discussions on dropping this requirement, but it was decided to keep it as it is.


(4) How can I import a module specifying the package name? I.E. from testmod.py, I would like to import testpackage.testmod2 rather than just testmod2.

This should work. Just ensure that you run the code from the top-level directory. If the current directory is testpackage, testmod does not know that it's in a package.

The preferred way is to use relative intra-package imports, though:

from . import testmod2

This prevents name clashes if there is a global module named testmod2 and enables you to use the names of well-known modules within your package without problems.


(5) What is the proper way to import submodules from the subsubs directory?The only solution I see is to append that directory to the pythonpath from __init__.py, but I don't know if that's the correct way.

No, don't do that! Never, ever put a directory to sys.path when one of it's parent directories already is in sys.path! This could cause your modules to be loaded twice, which is a bad thing!

Usually you should be able to load modules from subpackages using absolute or relative imports:

import testpackage.testsubs.testsubmod
from testpackage.testsubs import testsubmod
from .testsubs import testsubmod

Just make sure to create a __init__.py within testsubs/!

https://en.xdnf.cn/q/72501.html

Related Q&A

Finding location in code for numpy RuntimeWarning

I am getting warnings like these when running numpy on reasonably large pipeline. RuntimeWarning: invalid value encountered in true_divideRuntimeWarning: invalid value encountered in greaterHow do I fi…

Django, Angular, DRF: Authentication to Django backend vs. API

Im building an app with a Django backend, Angular frontend, and a REST API using Django REST Framework for Angular to consume. When I was still working out backend stuff with a vanilla frontend, I used…

Django view testing

Im trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object?

Remove non-ASCII characters from string columns in pandas

I have panda dataframe with multiple columns which mixed with values and unwanted characters. columnA columnB columnC ColumnD \x00A\X00B NULL \x00C\x00D 123 \x00E\X00F…

Open source Twitter clone (in Ruby/Python) [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

What is the best way to connect to a Sybase database from Python?

I am trying to retrieve data in a Sybase data base from Python and I was wondering which would be the best way to do it. I found this module but may be you have some other suggestions: http://python-sy…

How to get N random integer numbers whose sum is equal to M

I want to make a list of N random INTEGER numbers whose sum is equal to M number.I have used numpy and dirichlet function in Python, but this generate double random number array, I would like to genera…

Why sqlalchemy declarative base object has no attribute query?

I created declarative table. from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String from sqlalchemy.dialects.postgresql import UUID import uuidBase = declarative_…

Django ModelForm not saving data

Ive tried solutions from the following posts: Saving data from ModelForm : Didnt workModelForm data not saving django : Didnt work. Im trying to save data from a ModelForm into the model. models.py:cla…

When is it appropriate to use sample_weights in keras?

According to this question, I learnt that class_weight in keras is applying a weighted loss during training, and sample_weight is doing something sample-wise if I dont have equal confidence in all the …