-1

I need to import a single class (not the whole file) from a python file starting with number. There was a topic on importing a whole module and it works, but can't find my way around this one. (In python, how to import filename starts with a number)

Normally it would be:

from uni_class import Student

though the file is called 123_uni_class.

Tried different variations of

importlib.import_module("123_uni_class")

and

uni_class=__import__("123_uni_class")

Error:

    from 123_uni_class import Student
            ^
 SyntaxError: invalid decimal literal
Iguananaut
  • 21,810
  • 5
  • 50
  • 63
Minka
  • 9
  • 2
    Please paste the full traceback. I don't think you would get a SyntaxError here unless somewhere else you actually wrote the line `from 123_uni_class import Student`. In general I think you should just rename your module though. In general there's no good reason to try to do this. – Iguananaut Dec 08 '19 at 11:16
  • well, that's what I'm talking about, I want to do that, but can't bcs of this error – Minka Dec 08 '19 at 14:26
  • So, remove or rewrite that line. Please see my updated answer. – Iguananaut Dec 09 '19 at 10:28

2 Answers2

3

importlib.import_module("123_uni_class") returns the module after importing it, you must give it a valid name in order to reuse it:

import importlib

my_uni_class = importlib.import_module("123_uni_class")

Then you can access your module under the name 'my_uni_class'.

This would be equivalent to import 123_uni_class as my_uni_class if 123_uni_class were valid in this context.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
-1

It works for me:

Python 3.6.8 (default, Feb 14 2019, 22:09:48)
[GCC 7.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> importlib.import_module('123_a')
<module '123_a' from '/path/to/123_a.py'>
>>> __import__('123_a')
<module '123_a' from '/path/to/123_a.py'>

You would not see an actual syntax error containing the literal text "from 123_uni_class import ..." unless you actually have some source code containing that line.

If you must, you can also bypass the import system entirely by reading the contents of the file and exec()-ing them, possibly into a namespace you provide. For example:

mod = {}
with open('123_uni_class.py') as fobj:
    exec(fobj.read(), mod)

Student = mod['Student']

This general technique is used, for example, to read config files written in Python and things like that. I would discourage it though for normal usage and suggest you just use a valid module name.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63